- 二叉树的直径
一个节点的最大直径 = 它左树的高度 + 它右树的高度
/**
* 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;
}
}