LeetCode513 找树左下角的值(BFS)

LeetCode513 找树左下角的值(BFS)

BFS算法层层遍历,记录每层的最左边的结点的值

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def findBottomLeftValue(self, root: TreeNode) -> int:
        q = []
        q.append(root)
        while q:
            ans = q[0].val
            n = len(q)
            for i in range(n):
                tmp = q.pop(0)
                if tmp.left:
                    q.append(tmp.left)
                if  tmp.right:
                    q.append(tmp.right)
        return ans

猜你喜欢

转载自blog.csdn.net/qq_42991793/article/details/87925013