代码随想录day16|104. 二叉树的最大深度
class Solution {
public int maxDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int count = 0;
if(root == null)return 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0 ; i < size ; i++){
TreeNode node = queue.poll();
if(node.left!=null)queue.offer(node.left);
if(node.right != null)queue.offer(node.right);
}
count++;
}
return count;
}
}
class Solution {
public int maxDepth(TreeNode root) {
if(root == null)return 0;
return Math.max(maxDepth(root.right) , maxDepth(root.left))+1;
}
}
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
int count = 0;
if(root == null)return 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
count++;
for(int i = 0 ; i < size ; i++){
TreeNode node = queue.poll();
if(node.left==null && node.right == null)return count;
if(node.left!=null)queue.offer(node.left);
if(node.right != null)queue.offer(node.right);
}
}
return count;
}
}
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) {
return rightDepth + 1;
}
if (root.right == null) {
return leftDepth + 1;
}
return Math.min(leftDepth, rightDepth) + 1;
}
}
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
if (leftDepth == rightDepth) {
return (1 << leftDepth) + countNodes(root.right);
} else {
return (1 << rightDepth) + countNodes(root.left);
}
}
private int getDepth(TreeNode root) {
int depth = 0;
while (root != null) {
root = root.left;
depth++;
}
return depth;
}
}