93. Balanced Binary Tree [easy]

Description

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.

Example

Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

题目不难,判断是不是平衡二叉树(AVL),得保证平衡因子为(1,-1,  0)之一。

思路一:直接按照定义,求出根的左子树、右子树的深度,得出平衡因子,递归求解

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
     public static int height(TreeNode root){
         if(root==null){
             return 0;
         }else return Math.max(height(root.left),height(root.right))+1;
     }
      
    public boolean isBalanced(TreeNode root) {
        // write your code here
        if(root==null)
        return true;
        else if(Math.abs(height(root.left)-height(root.right))>1)
        return false;
        //对每个子树进行判断
        return isBalanced(root.left)&&isBalanced(root.right);
}

思路二:在求子树的深度时,就判断子树的平衡因子是否满足条件,不满足返回-1,直接结束递归,即不是 height-balanced.。如果没发现哪个子树不满足条件,则返回自己的深度(一定大于等于0)。

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
        public static int depth(TreeNode root){
            //检查下自己
            if(root==null)
            return 0;
            //检查一下左子树
            int l=depth(root.left);
            if(l==-1)
            return -1;
            //检查一下右子树
            int r=depth(root.right);
            if(r==-1)
            return -1;
            //再检查一下自己
            if(Math.abs(l-r)>1)
            return -1;
            //如果都没问题,就返回自己的真实深度
            return 1+Math.max(l,r);
        }
    public boolean isBalanced(TreeNode root) {
        // write your code here
        if(depth(root)==-1) return false;
        else return true;
    }
}

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9068918.html