865. Smallest Subtree with all the Deepest Nodes
- Smallest Subtree with all the Deepest Nodes python solution
题目描述
Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.
A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in its subtree.
解析
和LeetCode1123解题思路一样,见博客
还是要采用递归的思想解题。如果最深节点只有一个,那么就返回该节点。如果有两个最深节点,返回这两个节点的上一个公共节点,就是一棵树。
关键点,如果左右节点都有值,返回该node,也就是对应上述的第二种情况。
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
def dfs(node):
if node is None: return 0,None
l=dfs(node.left)
r=dfs(node.right)
if l[0]==r[0]:
return l[0]+1,node
elif l[0]>r[0]:
return l[0]+1,l[1]
else:
return r[0]+1,r[1]
return dfs(root)[1]
Reference
https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/146808/One-pass