题目描述
Category:Easy Tree
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.
题目理解
给定一棵二叉树,计算树的周长。树的周长定义为树的子节点间最长的路径。
解题思路
递归
depth函数:遍历二叉树,在每个节点计算左子树和右子树的深度,同时更新ans的值(保证ans的值一直更新为最大值),每次执行返回左子树和右子树中高度更大的值,便于计算二叉树的最长周长。
最后,返回ans的值即为所求的最大周长。
思路借鉴:https://blog.csdn.net/danspace1/article/details/86556411
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.ans = 0
def depth(root):
if not root:
return 0
left = depth(root.left)
right = depth(root.right)
self.ans = max(self.ans, left + right)
return max(left, right) + 1
depth(root)
return self.ans
代码分析
Runtime:44ms 66.84%
MemoryUsage:15.1MB 100.00%
Time
2020.3.16 时间好快哦~不知道什么时候才能开学