码迷,mamicode.com
首页 > 其他好文 > 详细

1123. Lowest Common Ancestor of Deepest Leaves

时间:2020-01-09 11:52:53      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:common   else   target   sel   desc   ble   etc   def   pes   

link to problem

Description:

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.

Solution:

class Solution:
    def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
        
        def helper(node):
            if not node:
                return [node, 0]
            if not node.left and not node.right:
                return [node, 0]
            
            if not node.right:
                left_node, left_dep = helper(node.left)
                return [left_node, left_dep + 1]
            
            if not node.left:
                right_node, right_dep = helper(node.right)
                return [right_node, right_dep + 1]
            
            left_node, left_dep = helper(node.left)
            right_node, right_dep = helper(node.right)
            if left_dep > right_dep:
                return [left_node, left_dep + 1]
            elif left_dep < right_dep:
                return [right_node, right_dep + 1]
            else:
                return [node, left_dep + 1]
        
        return helper(root)[0]

 

Notes:

DFS

recursion

1123. Lowest Common Ancestor of Deepest Leaves

标签:common   else   target   sel   desc   ble   etc   def   pes   

原文地址:https://www.cnblogs.com/beatets/p/12170587.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!