Google
543 Diameter of Binary Tree

1. Question

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: Given a binary tree
1
1
2
/ \
3
2 3
4
/ \
5
4 5
Copied!
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.

2. Implementation

(1) DFS Recursion
思路: 这题其实和124找max path sum一样,基本的步骤都是先用postorder traversal 找出当前node的left path的信息,和right path的信息,然后用一个变量找出当前的信息加上左右两边信息的总和 与 当前已知的最大信息之间的较大者。返回的值则是当前的信息(节点的个数或者节点的值) 加上左右两边信息较大的一方
1
/**
2
* Definition for a binary tree node.
3
* public class TreeNode {
4
* int val;
5
* TreeNode left;
6
* TreeNode right;
7
* TreeNode(int x) { val = x; }
8
* }
9
*/
10
class Solution {
11
public int diameterOfBinaryTree(TreeNode root) {
12
int[] diameter = new int[1];
13
14
getDiameterOfTree(root, diameter);
15
return diameter[0];
16
}
17
18
public int getDiameterOfTree(TreeNode node, int[] diameter) {
19
if (node == null) {
20
return 0;
21
}
22
23
int leftDiameter = getDiameterOfTree(node.left, diameter);
24
int rightDiameter = getDiameterOfTree(node.right, diameter);
25
diameter[0] = Math.max(diameter[0], leftDiameter + rightDiameter);
26
return 1 + Math.max(leftDiameter, rightDiameter);
27
}
28
}
Copied!

3. Time & Space Complexity

DFS Recursion: 时间复杂度O(n), n为树node的个数, 空间复杂度O(n)