此题要找到一个二叉树最后一行的最左边的值。
由于是树状结构,通常采用递归的方式去求解。因为我们想要得到最深处的最左边的值,所以在返回值的同时,还需要记录一下左右子树的深度,来帮助判断哪边才是我们需要的值。因此重新定义个函数depthAndValue,该函数返回目标值和当前这棵树的深度。此时分情况讨论,当左右都没有子树的时候,肯定返回自身值,以及深度为1。当只有左子树的时候,则递归遍历root.left,同时深度加一。只有右子树时,也是如此。当左右子树都存在时,则判断两者返回的深度哪个更深,将更深的那个值以及深度进行返回。最后在主函数中调用depthAndValue函数,只需要第一个返回值即可。
此外,还可以采用BFS方式,每次保存每一层最左边的那个值即可,由于复杂度相同,没有啥本质区别,故不再赘述。
代码如下:
# 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 depthAndValue(self, root):
if root.left == None and root.right == None:
return root.val, 1
if root.left == None and root.right !=None:
val, depth = self.depthAndValue(root.right)
return val, depth+1
if root.left !=None and root.right == None:
val, depth = self.depthAndValue(root.left)
return val, depth+1
left_value, depth1 = self.depthAndValue(root.left)
right_value, depth2 = self.depthAndValue(root.right)
if depth1 >= depth2:
return left_value, depth1+1
else:
return right_value, depth2+1
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result, _ = self.depthAndValue(root)
return result