Problem description:

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.

Example:

1
2
3
4
5
6
Given a binary tree 
1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Solution:

If the longest path will include the root node, then the longest path must be the depth(root->right) + depth (root->left)
If the longest path does not include the root node, this problem is divided into 2 sub-problem: set left child and right child as the new root separately, and repeat step1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
self.max_d = 0
if not root:
return 0

def dfs(root):
if not root:
return 0
left = dfs(root.left)
right = dfs(root.right)
self.max_d = max(self.max_d, left+right)
return max(left, right)+1
dfs(root)
return self.max_d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int max_d= 0;
int diameterOfBinaryTree(TreeNode* root) {
/*
design a maxDepth function to calculate depth for left and right subtree
a global variable for maximum diameter
*/
if(!root) return 0;
maxDepth(root);
return max_d;

}

int maxDepth(TreeNode* root){
if(!root) return 0;
int left= 0, right= 0;
if(root->left) left= maxDepth(root->left);
if(root->right) right= maxDepth(root->right);

max_d= max(max_d, left+right);
return max(left, right)+1;
}
};

time complexity: $O(n)$
space complexity: $O(1)$
reference:
https://goo.gl/PFpQAY