104. 二叉树的最大深度
两种方式:1.求二叉树的高度 2.求二叉树的深度
本次用的是方法1,即通过求二叉树的高度得出结果,因为二叉树高度=深度
思路:
因为求二叉树高度需要遍历到最深层,然后一层一层返回并+1,因此需要用到后序遍历,类似于昨天的101. 对称二叉树,都是需要对节点的左右孩子情况判断结束后,再向上一层一层的返回结果。
也可以理解为从根节点出发,用1+max(左、右节点高度),然后一层一层向下遍历,分别求出每层节点左右孩子的最大高度然后再return +1
类似于101.对称二叉树,利用后序遍历,都是先递归判断左右孩子情况,然后再return处理中间节点
class Solution {
public int maxDepth(TreeNode root) {
if(root ==null) return 0;
return getDepth(root);
}
public int getDepth(TreeNode root){
if(root == null) return 0;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
return Math.max(leftDepth,rightDepth) + 1;
}
}
111.二叉树的最小深度
思路:(递归法和迭代法两种方法)
层序遍历法更容易理解
层序遍历模板差不多,在向队列插入头结点后,进入while循环,此时定义size用来记录当前层个数,内层循环每结束一次,都是代表进入二叉树的下一层。在内层循环,每弹出一个元素都要判断一下当前元素是否是叶子节点(没有孩子),如果是直接返回结果。如果不是继续添加孩子
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()){
int size = queue.size();
res ++;
while(size-- > 0){
TreeNode node = queue.poll();//当队列内当前层size不为空时,弹出当前层队列头元素
if(node.left == null && node.right == null) return res;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return res;
}
}
222.完全二叉树的节点个数
思路:
利用层序遍历,循环弹出队列元素,同时使用res++计数
递归:
public int countNodes(TreeNode root){
if(root == null) return 0;
int countLeft = countNodes(root.left);
int countRight = countNodes(root.right);
return countLeft + countRight +1 ;
}
迭代:
public int countNodes(TreeNode root){
if(root == null ) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int res = 0;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
while(size -- > 0){
TreeNode node = queue.poll();
res++;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}return res;
}