力扣222 完全二叉树的节点个数
java
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
TreeNode leftnode = root.left;
int leftdepth = 0;
TreeNode rightnode = root.right;
int rightdepth = 0;
while(leftnode != null) {
leftnode = leftnode.left;
leftdepth++;
}
while(rightnode != null) {
rightnode = rightnode.right;
rightdepth++;
}
if(rightdepth == leftdepth) return (2 << rightdepth) - 1;
else {
int leftnum = countNodes(root.left);
int rightnum = countNodes(root.right);
return 1 + leftnum + rightnum;
}
}
}
力扣111 二叉树的最小深度
java
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int leftdepth = minDepth(root.left);
int rightdepth = minDepth(root.right);
if(root.left == null && root.right != null) return 1 + rightdepth;
else if(root.left != null && root.right == null) return 1 + leftdepth;
else if(root.left == null && root.right == null) return 1;
else return 1 + Math.min(leftdepth, rightdepth);
}
}
力扣104 二叉树的最大深度
java
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftheight = maxDepth(root.left);
int rightheight = maxDepth(root.right);
int height = 1 + Math.max(leftheight, rightheight);
return height;
}
}