LeetCode 1123. Lowest Common Ancestor of Deepest Leaves解题报告(python)

1123. Lowest Common Ancestor of Deepest Leaves

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值