题目信息

  • 题目:剑指 Offer 55 - II. 平衡二叉树

  • 时间: 2020-08-16

  • 题目链接:Leetcode

  • tag: 平衡二叉树 深度优先搜索

  • 难易程度:简单

  • 题目描述:

    输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

示例1:

给定二叉树 [3,9,20,null,null,15,7]

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

返回 true

示例2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

1
2
3
4
5
6
7
      1
/ \
2 2
/ \
3 3
/ \
4 4

返回 false

注意

1
1. 1 <= 树的结点个数 <= 10000

解题思路

本题难点

树的深度 等于 左子树的深度右子树的深度 中的 最大值 +1 。

具体思路

后序遍历 + 剪枝 (从底至顶),思路是对二叉树做后序遍历,从底至顶返回子树深度,若判定某子树不是平衡树则 “剪枝” ,直接向上返回。

  • 当节点root 左 / 右子树的深度差 ≤1,则返回当前子树的深度,即节点 root 的左 / 右子树的深度最大值 +1( max(left, right) + 1
  • 当节点root 左 / 右子树的深度差 >2,则返回 −1 ,代表 此子树不是平衡树

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public boolean isBalanced(TreeNode root) {
return recur(root) != -1;
}

public int recur(TreeNode root){
//当 root 为空:说明越过叶节点,因此返回高度 0 ;
if(root == null){
return 0;
}
//当左(右)子树深度为 −1 :代表此树的 左(右)子树 不是平衡树,因此剪枝,直接返回 −1 ;
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;
}
}

复杂度分析:

  • 时间复杂度 O(N) : N 为树的节点数;最差情况下,需要递归遍历树的所有节点。
  • 空间复杂度 O(N) : 最差情况下(树退化为链表时),系统递归需要使用 O(N) 的栈空间。

其他优秀解答

解题思路

先序遍历 + 判断深度 (从顶至底)

思路是构造一个获取当前子树的深度的函数 depth(root) ,通过比较某子树的左右子树的深度abs(depth(root.left) - depth(root.right)) <= 1 是否成立,来判断某子树是否是二叉平衡树。若所有子树都平衡,则此树平衡。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
//abs(self.depth(root.left) - self.depth(root.right)) <= 1 :判断 当前子树 是否是平衡树;
//isBalanced(root.left) : 先序遍历递归,判断 当前子树的左子树 是否是平衡树;
//isBalanced(root.right) : 先序遍历递归,判断 当前子树的右子树 是否是平衡树;
return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}

private int depth(TreeNode root) {
if (root == null) return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}