[LeetCode](面试题55 - II)平衡二叉树

题目

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

示例 1:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回 true

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

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

返回 false

限制:

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

解题思路

解法一:先序遍历 + 深度(从顶至底)

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

算法流程:
isBalanced(root) 函数: 判断树 root 是否平衡

  • 1)特例处理: 若树根节点 root 为空,则直接返回 true;
  • 2)返回值: 所有子树都需要满足平衡树性质,因此以下三者使用 && 连接:
    • 2.1)abs(depth(root.left) - depth(root.right)) <= 1 :判断当前子树是否是平衡树;
    • 2.2)isBalanced(root.left) :判断当前子树的左子树是否是平衡树;
    • 2.3)isBalanced(root.right) :判断当前子树的右子树是否是平衡树;

depth(root) 函数: 计算树 root 的深度

  • 1)终止条件:当 root​ 为空,说明已越过叶节点,因此返回深度为 0 。
  • 2)递推步骤:
    • 2.1)计算节点 root​ 的左子树的深度 left = epth(root.left);
    • 2.2)计算节点 root​ 的右子树的深度 right = depth(root.right);
  • 3)返回值:返回此节点的深度,即 max(left, right) + 1。

解法二:后序遍历 + 剪枝 (从底至顶)

解法一容易想到,但会产生大量重复计算,时间复杂度较高。

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

算法流程:
recur(root) 函数:

  • 1)当 root 为空:说明越过叶节点,因此返回高度 0 ;
  • 2)当左(右)子树深度为 -1:代表此树的左(右)子树不是平衡树,因此剪枝,直接返回 −1 ;
  • 3)当节点 root 左 / 右子树的深度差 ≤ 1,则返回当前子树的深度,即节点 root 的左 / 右子树的深度最大值 +1,即 max(left, right) + 1 ;否则,直接返回 -1,代表此子树不是平衡树 。

isBalanced(root) 函数:
返回值: 若 recur(root) != -1 ,则说明此树平衡,返回 true; 否则返回 false。

代码

解法一:先序遍历 + 深度(从顶至底)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        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;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.max(left, right) + 1;
    }
}

解法二:后序遍历 + 剪枝 (从底至顶)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return recur(root) != -1;
    }
    
    private 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)<=1 ? Math.max(left, right) + 1 : -1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章