树——判断是否为平衡二叉树

题目:balanced-binary-tree

判断一棵二叉树是否为平衡二叉树,即二叉树的每个结点的两棵子树的高度差不大于一。

方法一:

后序遍历二叉树,每遍历一个节点判断时候满足平衡条件,并存储该节点深度。

/**
 * 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) {
        int[]deepth={0};//存储该节点的深度;
        return isBalanced(root,deepth);
    }
    
    public boolean isBalanced(TreeNode root,int[]deepth)
        {
        if(root == null)
            return true;
        
        int []left={0};
        int []right={0};
        if(isBalanced(root.left,left)&&isBalanced(root.right,right))//判断条件的时候一定要仔细,不能随便return 
        {
            if(Math.abs(left[0]-right[0])<=1)
                {
                 deepth[0]=left[0]>right[0]?left[0]+1:right[0]+1;//该节点的深度公式,+1是精髓;
                return true;
            }
        }
        return false;
    }


方法二:


利用求二叉树深度函数deepth,在遍历每个结点的时候,调用deepth函数得到左右树的深度看相差是否在1以内。



代码如下:

public class Solution {
    
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
       
        boolean result=false;//不能写在函数外,否则返回的全是true;
        if(Math.abs(deepth(root.left)-deepth(root.right))<=1)
            {
            result=true;
        }
        
        if(result == true&&root.left!=null)
            result=isBalanced(root.left);
        if(result == true&&root.left!=null)
            result=isBalanced(root.right);
        
        return result;      
    }
    
    public int deepth(TreeNode root)
        {
        if(root == null)
            return 0;
        if(root.left == null&&root.right == null)
            return 1;
        
        return deepth(root.left)>deepth(root.right)?deepth(root.left)+1:deepth(root.right)+1;
    }
}


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 

你可能感兴趣的:(二叉树,平衡,后序遍历)