Diameter of Binary Tree

Diameter of Binary Tree

DFS 版本 - 64ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.length = 0
def depth(node):
if not node: return 0
left = depth(node.left)
right = depth(node.right)
self.length = max(self.length, left + right)
return 1 + max(left, right)
depth(root)
return self.length

leet code