1、104. 二叉树的最大深度
class solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int depth = 0;
if(root.children !=null){
for(Node node : root.children){
depth = Math.max(depth,maxDepth(node));
}
}
return depth +1 ;
}
}
2、111. 二叉树的最小深度
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int depth = 0;
while(!q.isEmpty()){
int len = q.size();
depth++;
for(int i=0;i<len;i++){
TreeNode cur = q.poll();
if(cur.left == null && cur.right == null) return depth;
if(cur.left !=null) q.add(cur.left);
if(cur.right !=null) q.add(cur.right);
}
}
return depth;
}
}
3、222. 完全二叉树的节点个数
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
int leftNodesCount = countNodes(root.left);
int rightNodesCount = countNodes(root.right);
int count = leftNodesCount+rightNodesCount+1;
return count;
}
}