leetcode算法: Find Bottom Left Tree Value Given a binary tree, find the leftmost value in the last row of the tree. Example 1:Input: 2 / \ 1 3 Output:1Example 2: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output:7Note: You may assume the tree (i.e., the given root node) is not NULL. 这道题 是 给我们一颗二叉树的根节点,让我们找到最后一层的最左边的节点。绞尽脑汁之后,利用二维数组把每个节点和所在层次扒下来了,但是还是太麻烦。看了其他大神的思路豁然开朗! 大神的思路是:从右向左广度优先遍历!! 最后一个节点就是我们要的结果!!献上我的代码:
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def findBottomLeftValue(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: int 13 """ 14 q = [root] 15 while q: 16 node = q.pop(0) 17 if node.right is not None: 18 q.append(node.right) 19 if node.left is not None: 20 q.append(node.left) 21 return node.val
时间: 2024-12-16 22:15:49