这是一道面试高频题,经常要手撕代码(牛客网看了一下大佬们对手撕代码的解释,xswl,哈哈哈我喜欢椒盐味的)。
虽然难度是 简单,但是对于初级者或粗心的人有坑🕳,我就是😔,我本质是个小菜鸡啊~
题目描述
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
Given a binary tree, you need to compute 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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法
这次就写写思路及踩坑、优化过程,因为这道题也没太多解法。然后是看了一个题解,跟他的心路历程简直一样的hhh,所以在这里引用一下~
首先,掉坑里。
最大直径,就是左子树最大高度+右子树最大高度啊!
然后马上码代码,测试用例正确,然后点提交,解答错误。
🙂
然后,是修改后。
代码如下:
class Solution
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
def maxDepth(root):
if not root:
return 0
return 1+max(maxDepth(root.left),maxDepth(root.right))
depth = maxDepth(root.right)+maxDepth(root.left)
right = self.diameterOfBinaryTree(root.right)
left = self.diameterOfBinaryTree(root.left)
return max(depth,right,left)
运行结果:
哇靠!这个耗时,我不能再快了,真的…但是胜在思路清晰,我如此安慰自己道…
最后,是优化后。
没有使用全局变量,参考题解 再初始化函数里添加了一个变量存储最大直径。
在递归中直接对比,减少重复计算。
class Solution:
def __init__(self):
self.maxdepth = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
def maxDepth(root):
global maxdepth
if not root:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
self.maxdepth = max(self.maxdepth, right+left)
return 1+max(left, right)
maxDepth(root)
return self.maxdepth
运行结果: