找树左下角的值
1.两种解法
迭代法–层序遍历
使用层序遍历,每遍历到一个节点,就把该节点的值存入result中。遍历到最后一层时记录下该层节点数量,记为index,然后返回result[-index]即可
代码如下:
def findBottomLeftValue(root):
queue = []
result = []
index = 0
if root:
queue.append(root)
while queue:
size = len(queue)
index = size
for i in range(size):
node = queue.pop(0)
result.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result[-index]
递归法–前序遍历
要想找到最后一层的最左边的节点,我们不能一直向左遍历该树,因为你不能保证该树的最左边的节点是最后一层的。所以我们要先找到最后一层的节点,这个我们用递归高度来实现;然后再找到该节点的最左边的节点,这个我们用前序遍历来实现,因为对于前序遍历而言,要先遍历左孩子,然后才遍历右孩子,所以我们只要判断有左孩子的话,那么右孩子的值就不覆盖了。
代码如下:
def findBottomLeftValue(root):
max_depth = -float("INF") # 存放最大深度用于比较
leftmost_val = 0 # 存放最左边节点的值
def traverse(root,cur_depth):
nonlocal max_depth,leftmost_val # 注意这个nonlocal声明,只能在python3中使用
if not root.left and not root.right: # 判断该节点是否为叶子节点
# 如果深度比max_depth要大,那么就更新
if cur_depth > max_depth: # 注意这个 “>” ,起到了记录同一层最左边节点的作用
# 更新
leftmost_val = root.val
max_depth = cur_depth
# 注意回溯,因为判断完该节点的左孩子之后还要判断右孩子,所以要把cur_depth再减回来
if root.left:
cur_depth += 1
traverse(root.left,cur_depth)
cur_depth -= 1
if root.right:
cur_depth += 1
traverse(root.right,cur_depth)
cur_depth -= 1
traverse(root,0)
return leftmost_val
2.总结
python
-
float(“INF”):表示一个很大的值
-
nonlocal和global:
(1)global1.如果要在内部函数中 修改 外部定义的变量,要声明global,即: gcount = 0 def global_test(): global gcount gcount+=1 print (gcount) global_test() 2.如果要在内部函数中 访问 外部定义的变量,则不用声明global,即: gcount = 0 def global_test(): print (gcount) global_test()
(2)nonlocal
nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量,即: def make_counter(): count = 0 def counter(): nonlocal count count += 1 return count return counter
算法
- 认真审题,不要盲目认为最左边的节点就是答案。
- 回溯的思想。使用前序遍历的原因。判断叶子节点的方法。