Daily Leetcode 513. Find Bottom Left Tree Value

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

Medium

问题描述:

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

1
2
3
4
5
6
7
8
Input:

2
/ \
1 3

Output:
1

Example 2:

1
2
3
4
5
6
7
8
9
10
11
12
Input:

1
/ \
2 3
/ / \
4 5 6
/
7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

题目分析:

所谓leftmost,就是要找到给定二叉树最深层次、位置在最左边的那个节点,二叉树相关的问题基本上都可以转换成树的遍历的问题。我们可以以先序顺序遍历给定二叉树,在遍历过程中,更新最大深度和对应的最大值,只有当前节点的深度大于遍历至今保存的最大深度时,才进行上述更新操作。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.currentMaxVal = root.val
self.currentMaxDepth = 0

def helper(root, depth):
if not root:
return 0

if depth > self.currentMaxDepth:
self.currentMaxVal = root.val
self.currentMaxDepth = depth

if root.left:
helper(root.left, depth + 1)

if root.right:
helper(root.right, depth + 1)

helper(root, 1)

return self.currentMaxVal