注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
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].
Example 2:
root = [1,2]
Input: root = [1,2]
res = 1- class Solution:
- def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
- res = 0
- self.helper(root, res)
- return res
- def helper(self, root, res):
- if not root:
- return 0
- left_path = self.helper(root.left, res)
- right_path = self.helper(root.right, res)
- res = max(res, left_path + right_path)
- 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吗?
|