查看: 251|回复: 0
收起左侧

[树/链表/图] 加米 lc543. Diameter of Binary Tree 的recursion

|只看干货
本楼: 👍   0% (0)
 
 
0% (0)   👎
全局: 👍   100% (78)
 
 
0% (0)    👎

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
大家好
题目lc543. Diameter of Binary Tree有一点recursion function的疑问,请大家帮忙看看,会尽力加米。
题目:https://leetcode.com/problems/diameter-of-binary-tree/
Given the root of a binary tree, return the length of the diameter of the tree.


The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.


The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

diamtree.jpg


Example 2:
root = [1,2]
Input: root = [1,2]
res = 1
  1. class Solution:
  2.     def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
  3.         res = 0
  4.         self.helper(root, res)
  5.         return res
  6.     def helper(self, root, res):
  7.         if not root:
  8.             return 0
  9.         left_path = self.helper(root.left, res)
  10.         right_path = self.helper(root.right, res)
  11.         res = max(res, left_path + right_path)
  12.         return max(left_path, right_path) + 1
复制代码
我的疑问是recurision call的base case和返回值,尤其是base case应该选not root还是not root.left and not root.right. 我的理解是
self.helper(root, res)要返回的值是height of a node, which is the number of edges on longest downward path between that node and a leaf, which is root的max(left branch path,right branch path).

For a node, the length of longest path going through the node is the sum of left childs height plus right child's height.

在这种情况下,我认为base case应该是root.left is none and root.right is none,这样self.helper(root, res)的返回值0, height of leaf node is 0.

用example1举例就是:
helper(4) = 0, helper(5) = 0, res = max(res, 0+0) = 0
helper(2) = 1, helper(3) = 0, res = max(res, 1+0) = 1, 这样的result是错的。

----------------唔,问题提到这里,我明白了错在哪里;self.helper(root,res)返回的是height of current node's parent; 这样才能满足 res = max(res, left_path + right_path). 我的自然语言描述太混乱了, 思路清晰的朋友可以帮忙顺一下base case, recursion call的作用,和recursion rule吗?







评分

参与人数 1大米 +5 收起 理由
14417335 + 5 给你点个赞!

查看全部评分


上一篇:lc近期公司高频题号(美区)
下一篇:这道变种题怎么实现1209变种
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表