Ideas
算法:递归
数据结构:二叉树
Code
时间复杂度:O(N)
其中 N 为二叉树的节点数,即遍历一棵二叉树的时间复杂度,每个结点只被访问一次。
空间复杂度:O(Height)
其中 Height 为二叉树的高度。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
ans = 0
def depth(node):
# 访问到空节点了,返回0
if not node:
return 0
# 左儿子为根的子树的深度
L = depth(node.left)
# 右儿子为根的子树的深度
R = depth(node.right)
# 更新ans
nonlocal ans
ans = max(ans, L + R)
# 返回该节点为根的子树的深度
return max(L, R) + 1
depth(root)
return ans