给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
注意:两结点之间的路径长度是以它们之间边的数目表示。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int Max = 0;
public int diameterOfBinaryTree(TreeNode root) {
MaxDepth(root);
return Max;
}
public int MaxDepth(TreeNode root){
if(root == null){
return 0;
}
int LeftMax = MaxDepth(root.left);
int RightMax = MaxDepth(root.right);
//后序遍历代码位置
int CurMax = LeftMax + RightMax;
Max = Math.max(Max,CurMax);
return Math.max(LeftMax,RightMax) + 1;
}
}