二叉树的最大深度:
首先就要区分高度和深度
深度: 任意一个节点到根节点的距离 用前序遍历
高度: 任意一个节点到叶子节点的距离 用后序遍历
这里用后序遍历是因为, 根节点的高度正好就是最大深度
递归法: 左右中
(由于他这个在叶子节点时设定的高度是0, 所以最后要加一)
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
//当他孩子指向空时, 高度显示是0, 所以要加1表示当前节点的高度
int maxDepth = Math.max(leftDepth, rightDepth) + 1;
return maxDepth;
}
}
层序遍历,迭代法:
和层序遍历的方法很想, 最大深度就是层数, 只要定义一个depth, 每一层循环depth++就行了, 也不需要二维数组和数组了
class Solution {
public int maxDepth(TreeNode root) {
//层序遍历, 最大深度也就是层数
Deque<TreeNode> deque = new LinkedList<>();
if(root == null){
return 0;
}
//定义深度, 等下循环记录
int depth = 0;
deque.offer(root);
while(!deque.isEmpty()){
int size = deque.size();
depth++;
while(size-- > 0){
TreeNode node = deque.poll();
if(node.left != null){
deque.offer(node.left);
}
if(node.right != null){
deque.offer(node.right);
}
}
}
return depth;
}
}
二叉树的最小深度:
递归法: 也是用后序遍历
这里有个陷阱, 不能简单的取Math.min, 因为会有如下情况, 他会直接取到左子树, 最小值为1, 但由于问的是根节点到叶子节点的最小距离, 所以要加个两个if循环判断:
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftD = minDepth(root.left);
int rightD = minDepth(root.right);
//判断左右孩子为null的情况
if(root.left == null){
return rightD + 1;
}
if(root.right == null){
return leftD + 1;
}
return Math.min(leftD, rightD) + 1;
}
}
迭代法, 层序遍历:
因为层序遍历是从上往下一层层的, 所以只要在每一层的循环中, 碰到了叶子节点, 就可以return.
加了一个&&的判断条件, 其他和层序遍历都是一模一样的
class Solution {
public int minDepth(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
if(root == null){
return 0;
}
deque.offer(root);
int depth = 0;
while(!deque.isEmpty()){
int len = deque.size();
depth++;
while(len-- > 0){
TreeNode cur = deque.poll();
//这里是重点, 如果遍历到叶子节点了就直接return
if(cur.left == null && cur.right == null){
return depth;
}
if(cur.left != null){
deque.offer(cur.left);
}
if(cur.right != null){
deque.offer(cur.right);
}
}
}
return depth;
}
}
完全二叉树的节点个数
思路:
普通二叉树解法, 直接用后序遍历
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int countLeft = countNodes(root.left);
int countRight = countNodes(root.right);
return countLeft + countRight + 1;
}
}
//或者直接一行代码就搞定了
return countNodes(root.left) + countNodes(root.right) + 1;
完全二叉树解法: 从左到右节点不能断开
满二叉树的情况: 2^深度次方-1
比较最左边深度和最右边深度
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftD = getDepth(root.left);
int rightD = getDepth(root.right);
if(leftD == rightD){
return(1 << leftD) + countNodes(root.right);
} else {
return(1 << rightD) + countNodes(root.left);
}
}
private int getDepth(TreeNode root){
int depth = 0;
while(root != null){
root = root.left;
depth++;
}
return depth;
}
}