104.二叉树的最大深度
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
思路:可以层序遍历,也可以前序和后序,递归就是统计左右孩子长度取其大值
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;
}
}
题目链接:559. N 叉树的最大深度 - 力扣(LeetCode)
class Solution {
public int maxDepth(Node root) {
if(root == null) return 0;
int depth = 0;
if(root.children != null){
for(Node child : root.children){
depth = Math.max(depth,maxDepth(child));
}
}
return depth+1;
}
}
111.二叉树的最小深度
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
思路:返回条件是左右子树为null,所以先进入最左子树,然后再去最右子树,确定到最底端,再返回,注意一个子树为空,一个子树不为空不是最小的深度。
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 rightDepth+1;
if(root.right == null && root.left != null) return leftDepth+1;
return Math.min(leftDepth,rightDepth)+1;
}
}
222.完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftSize = countNodes(root.left);
int rightSize = countNodes(root.right);
return leftSize+rightSize+1;
}
}
432





