当前位置: 首页 > 工具软件 > Leaves > 使用案例 >

1123. Lowest Common Ancestor of Deepest Leaves

邴宏大
2023-12-01

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 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.

 

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]
                

 

 类似资料:

相关阅读

相关文章

相关问答