给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
class Solution {
int max = 0;
public int dfs(TreeNode root){
if(root == null)
return 0;
int leftH = dfs(root.left);
int rightH = dfs(root.right);
max = Math.max(max,leftH + rightH);
return Math.max(leftH,rightH) + 1;
}
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
dfs(root);
return max;
}
}
class Solution {
int max = 0;
public int dfs(TreeNode root){
if(root == null)
return 0;
return Math.max(dfs(root.left),dfs(root.right)) + 1;
}
public int diameterOfBinaryTree(TreeNode root) {
if(root == null)
return 0;
int leftH = dfs(root.left);
int rightH = dfs(root.right);
max = Math.max(max,leftH + rightH);
diameterOfBinaryTree(root.left);
diameterOfBinaryTree(root.right);
return max;
}
}
根节点为root的二叉树的直径 = max(root.left的直径,root.right的直径,
root.left的最大深度+root.right的最大深度+1) |