zoukankan      html  css  js  c++  java
  • Balanced Binary Tree

    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
  • 相关阅读:
    简单算法系列之完数的计算
    毕业了
    通过代码实现截取一定字符的实现
    写点做完一个小项目的教训....
    关于ListView下隐藏控件的解决方案
    用C#实现古代诗词的竖排文字
    获得在查询分析器里执行程序的精确时间以及查询效率问题
    要成功必须知道的12个秘诀!
    WAT网站压力测试工具
    wap网站开发相关知识
  • 原文地址:https://www.cnblogs.com/hf-cherish/p/4598832.html
Copyright © 2011-2022 走看看