1、最大深度问题
1、法一:递归
与后序遍历类似,先算出左右子树的结果再进行相关操作。
public static int maxDepth_1(TreeNode root) {
if (root == null) return 0;
int left = maxDepth_1(root.left);
int right = maxDepth_1(root.right);
return Math.max(left, right) + 1;
}
2、法二:层次遍历法
在以层为单位操作时,每层操作结束,将层数+1。
与之前的层次遍历 类似。
public static int maxDepth_2(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
//一层个数
int size = queue.size();
//某层节点出队后,将它的下一层入队
for (int i = 0; i < size; i++) {
TreeNode tmp = queue.poll();
if (tmp.left != null) {
queue.add(tmp.left);
}
if (tmp.right != null) {
queue.add(tmp.right);
}
}
//层数++
ans++;
}
return ans;
}
2、判断平衡树
1、法一:自上而下
通过自上而下遍历每个节点,并且对每个节点的左右节点深度做对比。
public static boolean isBalance_1(TreeNode root){
if(root == null) return true;
return Math.abs(maxDepth(root.left)-maxDepth(root.right)) < 2 && isBalance_1(root.left) && isBalance_1(root.right);
}
public static int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
2、法二:自下而上
通过自下而上遍历每个节点,并且计算差值是否平衡,不平衡返回-1直到最上层,表示不平衡。
若某节点左右平衡,则把它的高度返回,以便上层节点计算差值。
public static boolean isBalance_2(TreeNode root){
return recur(root) != -1;
}
public static int recur(TreeNode root){
if(root == null) return 0;
int left = recur(root.left);
if(left == -1) return -1;
int right = recur(root.right);
if(right == -1) return -1;
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}