HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. Question

判断一个树是否是平衡二叉树(每个节点的两个子树深度差不超过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 1.

2. Solution

考虑特殊情况:

  • 树为空

采用分治法:

  • 左子树是平衡二叉树
  • 右子树是平衡二叉树
  • 左子树与右子树高度差<=1

利用栈实现非递归方法,其中节点值存放以该节点为根的树深度,即叶子节点深度为1。先找最左或最右的两个子树,计算高度,判断是不是平衡的。然后依次向上找。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //whether b is the child of a
    public boolean isChild( TreeNode a, TreeNode b ){
        boolean res=false;
        if( a.left!=null ) res = a.left.equals(b);
        if( a.right!=null ) res = res || a.right.equals(b);
        return res;
    }
    
    //true if a is a leaf, or, false
    public boolean isLeaf( TreeNode a ){
        return a.left==null && a.right==null;
    }
    
    public boolean isBalanced( TreeNode root ){
        if( root==null ) return true;
        Stack<TreeNode> st = new Stack<TreeNode>();
        st.push(root);
        TreeNode present;
        TreeNode before = root;
        
        while( !st.isEmpty() ){
            present = st.peek();
            if( isLeaf(present) ){
                present.val = 1;
                before = present;
                st.pop();
                continue;
            }
            if( isChild(present, before) ){
                int left=0;
                int right=0;
                if( present.left==null )
                    right = present.right.val;
                else if( present.right == null )    left = present.left.val;
                else{
                    left = present.left.val;
                    right = present.right.val;
                }
                if( Math.abs(left-right) >1 ) return false;
                present.val = ( left>right ? left : right ) + 1;
                before = present;
                st.pop();
                continue;
            }
            if( present.left != null ) st.push(present.left);
            if( present.right != null ) st.push(present.right);
        }
        
        return true;
    }
}
View Code

 

posted on 2015-06-24 22:35  HF_Cherish  阅读(129)  评论(0编辑  收藏  举报