思路
test cases: the path with the longest length may go through the root, or it may be in left subtree or right subtree without going through the root based on the test cases, we need to check the diameter of each node we meet time complexity: O(n), space complexity: O(n) stack space
方法1:divide-and-conquer, use global variable
class Solution :
def diameterOfBinaryTree ( self, root: TreeNode) - > int :
if root is None :
return 0
self. longest = 0
self. dfs( root)
return self. longest
def dfs ( self, root) :
if root is None :
return 0 , 0
lleft, lright = self. dfs( root. left)
rleft, rright = self. dfs( root. right)
left = max ( lleft, lright) + 1
right = max ( rleft, rright) + 1
self. longest = max ( self. longest, left + right - 2 )
return left, right
方法2:use divide-and-conquer, longest length is in the return values
class Solution :
def diameterOfBinaryTree ( self, root: TreeNode) - > int :
if root is None :
return 0
_, _, longest = self. dfs( root)
return longest
def dfs ( self, root) :
if root is None :
return 0 , 0 , 0
lleft, lright, llongest = self. dfs( root. left)
rleft, rright, rlongest = self. dfs( root. right)
left = max ( lleft, lright) + 1
right = max ( rleft, rright) + 1
longest = max ( llongest, rlongest, left + right - 2 )
return left, right, longest