Problem: 543. 二叉树的直径
文章目录
- 思路 & 解题方法
- 复杂度
- Code
思路 & 解题方法
二叉树递归
复杂度
时间复杂度:
空间复杂度:
Code
# 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: Optional[TreeNode]) -> int:
if not root:
return 0
L = self.diameterOfBinaryTree(root.left)
R = self.diameterOfBinaryTree(root.right)
ans = 0
if root.left and root.right:
root.val = max(root.left.val, root.right.val) + 1
ans = root.left.val + root.right.val
elif not root.left and not root.right:
root.val = 1
ans = 0
else:
root.val = root.left.val + 1 if root.left else root.right.val + 1
ans = root.val - 1
return max([L, R, ans])