104.二叉树的最大深度
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
递归法1:
class Solution {
public int maxDepth(TreeNode root) {
// 递归法
if(root == null) return 0;
int leftmax = maxDepth(root.left);
int rightmax = maxDepth(root.right);
return Math.max(leftmax,rightmax) + 1;
}
}
递归法2:
class Solution {
int max;
public int maxDepth(TreeNode root) {
// 递归法
max = 0;
if(root == null) return max;
findmax(root,0);
return max;
}
public void findmax(TreeNode root, int deep){
deep++;
if(root == null) return;
if(max < deep) max = deep;
findmax(root.left, deep);
findmax(root.right, deep);
}
}
迭代法:通过层序遍历看一共多少层
class Solution {
public int maxDepth(TreeNode root) {
// 迭代法
int depth = 0;
if(root == null) return depth;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
depth++;
int size = que.size();
while(size-- > 0){
TreeNode cur = que.poll();
if(cur.left != null) que.offer(cur.left);
if(cur.right != null) que.offer(cur.right);
}
}
return depth;
}
}
111.二叉树的最小深度
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
递归:
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int leftmin = minDepth(root.left);
int rightmin = minDepth(root.right);
if(root.left == null && root.right != null) return 1 + rightmin;
if(root.left != null && root.right == null) return 1 + leftmin;
return 1 + Math.min(rightmin,leftmin);
}
}
迭代: 层序遍历,当遍历到一个节点其左右孩子都为空的时候,返回当前深度
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> que = new LinkedList<>();
if(root == null) return 0;
que.offer(root);
int depth = 0;
while(!que.isEmpty()){
depth++;
int size = que.size();
while(size-- > 0){
TreeNode cur = que.poll();
if(cur.left == null && cur.right == null) return depth;
if(cur.left != null) que.offer(cur.left);
if(cur.right != null) que.offer(cur.right);
}
}
return depth;
}
}
222.完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
递归:
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}
层序遍历迭代:
class Solution {
public int countNodes(TreeNode root) {
Queue<TreeNode> que = new LinkedList<>();
if(root == null) return 0;
que.offer(root);
int length = 0;
while(!que.isEmpty()){
int size = que.size();
length += size;
while(size-- > 0){
TreeNode cur = que.poll();
if(cur.left != null) que.offer(cur.left);
if(cur.right != null) que.offer(cur.right);
}
}
return length;
}
}