int depth = 0;
int maxDepth = 0;
public int maxDepth(TreeNode root) {
maxDepth = traverse(root);
return maxDepth;
}
public int traverse(TreeNode root){
if(root == null){
return 0;
}
int left = traverse(root.left);
int right = traverse(root.right);
maxDepth = left>=right?left:right;
maxDepth++;
// 访问root,高度+1
return maxDepth;
}
/*如何打印出每个节点的左右子树各有多少节点*/
public static int traverseRootCount(TreeNode root) {
if (root == null) {
return 0;
}
int leftCount = traverseRootCount(root.left);
int rightCount = traverseRootCount(root.right);
System.out.printf("当前节点为%d, 它的左子树有%d个节点, 右子树有%d个节点\n", root.val, leftCount, rightCount);
return leftCount + rightCount + 1;
}
/*如何打印出每个节点的左右子树各有多少节点 与所在层次 */
public static int traverseRootCount(TreeNode root, int level) {
if (root == null) {
return 0;
}
level++;
int leftCount = traverseRootCount(root.left, level);
int rightCount = traverseRootCount(root.right, level);
System.out.printf("当前节点为%d, 位于第%d层, 它的左子树有%d个节点, 右子树有%d个节点\n",
root.val, level, leftCount, rightCount);
return leftCount + rightCount + 1;//返回节点个数
}
力扣 543 二叉树的直径
java复制代码
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
// 二叉树最长直径 即 二叉树 左右子树最长深度之和
// 对所有节点都求一次直径!!!!
if(root==null){
return 0;
}
int leftMax = depthMax(root.left);
int rightMax = depthMax(root.right);
max = Math.max(max,leftMax+rightMax);
return max;
}
public int depthMax(TreeNode root){
if(root == null){
return 0;
}
int left = depthMax(root.left) + 1;
int right = depthMax(root.right) + 1;
max = Math.max(max,left-1+right-1);
// 更新最大直径的值 直到最后一次递归最外层函数时 计算 以最初的root为根的最大直径
return Math.max(left,right);
}