- 二叉樹的直徑
一個節點的最大直徑 = 它左樹的高度 + 它右樹的高度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//解法1 遞歸+ 全局變量
private int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
maxDepth(root);
return max;
}
private int maxDepth(TreeNode root){
if(root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
//記錄最大值
max = Math.max((leftDepth + rightDepth),max);
return Math.max(leftDepth,rightDepth) + 1;
}
//解法2 不使用全局變量
public int diameterOfBinaryTree(TreeNode root) {
final int[] max = {0};
DFS(root,max);
return max[0];
}
public int DFS(TreeNode root,int[] max){
if(root == null)
return 0;
int left = DFS(root.left,max);
int right = DFS(root.right,max);
//獲取最大值
max[0] = Math.max((left + right),max[0]);
//返回遞歸樹的最大高度
return Math.max(left,right) + 1;
}
}