題目分析
根據題目,我們可以轉換思想到求二叉樹的深度,其中左子樹深度加上右子樹深度就是二叉樹某一個節點的直徑,在這個過程中使用一個全局變量記錄最大解即可。
Java代碼
public int res;
public int diameterOfBinaryTree(TreeNode root) {
res = 0;
depth(root);
return res;
}
private int depth(TreeNode root){
if(root == null){
return 0;
}
int left = depth(root.left);
int right = depth(root.right);
System.out.println("root = " + root.val);
System.out.println("left = " + left);
System.out.println("right = " + right);
// 返回根節點深度
res = Math.max(res,left+right+1);
return Math.max(left,right) + 1;
}