Given a rooted binary tree, find the lowest common ancestor of its deepest leaves.
Recall that:
d
, the depth of each of its children is d+1
.S
of nodes is the node A
with the largest depth such that every node in S is in the subtree with root A
.
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:
思路:求出所有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]