LeetCode 865. [python] Smallest Subtree with all the Deepest Nodes
原题链接
中等
作者:
徐辰潇
,
2020-03-06 07:00:02
,
所有人可见
,
阅读 666
class Solution:
def helper(self, root, depth):
if root.left is None and root.right is None:
if depth == 0:
self.res_node = root
if depth > self.maxdepth:
self.maxdepth = depth
self.res_node = root
return depth
if root.left and root.right:
leftMax = self.helper(root.left, depth + 1)
rightMax = self.helper(root.right, depth + 1)
if leftMax == rightMax:
if leftMax >= self.maxdepth:
self.res_node = root
self.maxdepth = leftMax
return max(leftMax, rightMax)
elif root.left:
return self.helper(root.left, depth + 1)
else:
return self.helper(root.right, depth + 1)
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
self.maxdepth = 0
self.res_node = None
self.helper(root, 0)
return self.res_node