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