LeetCode 865. Smallest Subtree with all the Deepest Nodes解题报告(python)

865. Smallest Subtree with all the Deepest Nodes

  1. Smallest Subtree with all the Deepest Nodes python solution

题目描述

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.
A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

在这里插入图片描述

解析

和LeetCode1123解题思路一样,见博客
还是要采用递归的思想解题。如果最深节点只有一个,那么就返回该节点。如果有两个最深节点,返回这两个节点的上一个公共节点,就是一棵树。
关键点,如果左右节点都有值,返回该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/smallest-subtree-with-all-the-deepest-nodes/discuss/146808/One-pass

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值