513. 找树左下角的值

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

解法一:层序

每个节点按先右后左顺序,则最后访问的一定是左下角。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue
class Solution:
    def findBottomLeftValue(self, root: TreeNode) -> int:
        if not root:
            return
        q = queue.Queue()
        q.put(root)
        work = None    #工作节点
        while not q.empty():
            count = q.qsize()
            for _ in range(count):
                work = q.get()
                if work.right:
                    q.put(work.right)
                if work.left:
                    q.put(work.left)
        return work.val    #最后一次访问的结点

最后更新于