104 二叉树的最大深度
https://leetcode.cn/problems/maximum-depth-of-binary-tree/
可以BFS记录一个depth每层++,这里用DFS后序遍历, 用DFS前中后序遍历也可以,但需要往下传入一个全局变量depth.
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
111 二叉树的最小深度
https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
BFS做法,遇到第一个叶子返回depth.
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new ArrayDeque<>();
int depth = 0;
if (root != null) queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
depth++;
while (size-- > 0) {
TreeNode cur = queue.poll();
if (cur.left == null && cur.right == null) return depth;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return depth;
}
}
DFS 不能直接写
{ if (root == null) return 0;
return Math.min(minLeft, minRight) + 1; }
同时为null时0都有效,其他时候为0时无效忽略改为MAX。
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int minLeft = minDepth(root.left);
int minRight = minDepth(root.right);
if (minLeft == 0 && minRight != 0) minLeft = Integer.MAX_VALUE;
if (minRight == 0 && minLeft != 0) minRight = Integer.MAX_VALUE;
return Math.min(minLeft, minRight) + 1;
}
}
222完全二叉树的节点个数
https://leetcode.cn/problems/count-complete-tree-nodes/
如果安照普通数的做法,DFS,BFS都可以做时间是O(n),如果考虑到保证是complete tree,那么左右可以不停分解成更小的complete tree直到右子树分解为complete tree. 每个complete tree的节点数为2^height - 1. 注意如果需要递归到下一层,参数是root.left/root.right而不是已经走到null的用来数左右高度的leftRoot, rightRoot.
class Solution { //每次递归里要while height次,总共递归height层,TO(logn * logn)
public int countNodes(TreeNode root) {
if (root == null) return 0;
int leftDeepth = 0, rightDepth = 0;
TreeNode leftRoot = root.left, rightRoot = root.right;
while (leftRoot != null) {
leftDeepth++;
leftRoot = leftRoot.left;
}
while (rightRoot != null) {
rightDepth++;
rightRoot = rightRoot.right;
}
if (leftDeepth == rightDepth) return (2 << leftDeepth) - 1;
return countNodes(root.left) + countNodes(root.right) + 1; //bug countNodes(leftRoot) + countNodes(rightRoot) + 1;
}
}