平衡二叉树


版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

题目大意

给定一颗二叉树,确定它是否是在高度上平衡的。
平衡二叉树的定义:一颗二叉树,它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

思路

根据平衡二叉树的定义:如果二叉树是空树,那便可以直接确定这棵二叉树是平衡的;如果二叉树非空,就判断它的左右子树高度差是否超过1;如果左右子树的高度差不超过1,再判断左右子树是否分别是一棵平衡二叉树。
在这里,判断左右子树高度差是否超过1时,用了一个函数isBalancedHelper(TreeNode root);,这个函数用递归方法计算二叉树的高度,并将高度返回;判断左右子树是否分别是一棵平衡二叉树时,采用的也是递归判断二叉树的左右子树分别是否为平衡二叉树(递归,真香!)。

代码

// Definition for binary tree
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null)return true;
        if((isBalancedHelper(root.left)-isBalancedHelper(root.right)>1)||(isBalancedHelper(root.left)-isBalancedHelper(root.right)<-1))
            return false;
        return isBalanced(root.left)&&isBalanced(root.right);
    }

    public int isBalancedHelper(TreeNode root){
        if(root == null) return 0;
        if(root.left==null&&root.right==null)return 1;
        int leftHeight = isBalancedHelper(root.left);
        int rightHeight = isBalancedHelper(root.right);
        return leftHeight > rightHeight ? (leftHeight+1):(rightHeight+1);
    }
}

以上。


版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


你可能感兴趣的:(平衡二叉树)