Given a rooted binary tree, find 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 isd+1
. - The lowest common ancestor of a set
S
of nodes is the nodeA
with the largest depth such that every node in S is in the subtree with rootA
.
Example 1:
Input: root = [1,2,3] Output: [1,2,3]
Example 2:
Input: root = [1,2,3,4] Output: [4]
Example 3:
Input: root = [1,2,3,4,5] Output: [2,4,5]
Constraints:
- The given tree will have between 1 and 1000 nodes.
- Each node of the tree will have a distinct value between 1 and 1000.
思路:求出所有leaf的path,然后暴力遍历
# 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 lcaDeepestLeaves(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
lfs = []
ps = []
def dfs(r):
if not r.left and not r.right:
ps.append(r)
lfs.append(list(ps))
ps.pop()
return
if r.left:
ps.append(r)
dfs(r.left)
ps.pop()
if r.right:
ps.append(r)
dfs(r.right)
ps.pop()
dfs(root)
ma = max([len(p) for p in lfs])
lfs = [p for p in lfs if len(p)==ma]
if len(lfs)==1: return lfs[0][-1]
for i in range(ma):
for j in range(1,len(lfs)):
if lfs[j][i]!=lfs[0][i]:
return lfs[0][i-1]