1123. Lowest Common Ancestor of Deepest Leaves
- Lowest Common Ancestor of Deepest Leaves python solution
题目描述
Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
The node of a binary tree is a leaf if and only if it has no children
The depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.
The lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.
解析
还是要采用递归的思想解题。如果最深节点只有一个,那么就返回该节点。如果有两个最深节点,返回这两个节点的上一个公共节点,就是一棵树。
关键点,如果左右节点都有值,返回该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/lowest-common-ancestor-of-deepest-leaves/discuss/336152/python-solution-Easy-to-understand.