leetcode110-平衡二叉树

原题

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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,获取高度通过递归实现。

自底向上:回溯时比较左右节点的高度,如果有任意节点左右子树高度差大于1,则说明不是平衡树。

代码

自顶向下:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        if(Math.abs(Height(root.left)-Height(root.right))>1) return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }
    public int Height(TreeNode root){
        if(root == null) return 0;
        int left = Height(root.left);
        int right = Height(root.right);
        if(left>=right) return left+1;
        else return right+1;
    }
}

自底向上:

public class BalancedBinaryTree {
    boolean res = true;

    public boolean isBalanced(TreeNode root) {
        helper(root);
        return res;
    }

    private int helper(TreeNode root) {
        if (root == null) return 0;
        int left = helper(root.left) + 1;
        int right = helper(root.right) + 1;
        if (Math.abs(right - left) > 1) res = false;
        return Math.max(left, right);
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode110-%e5%b9%b3%e8%a1%a1%e4%ba%8c%e5%8f%89%e6%a0%91/

发表回复

登录后才能评论