如何只遍历一次判断一棵二叉树是否为平衡二叉树

平衡二叉树的定义是对于二叉树中任何一个节点来说它的左子树和右子数的深度之差小于等于一。

        现在要只遍历一次判断一棵二叉树是否为平衡二叉树,这个问题可以这样分析,假设p为二叉树中的任何一个节点,f(p)表示以p为根节点的子树是否为平衡二叉树,则f(p)满足

   

1,当p不为null时,则f(p)为真,当且仅当f(pleft)为真,且f(pright)为真,且pleft和priht的深度之差小于等于1。否则f(p)为false。pleft表示p的左孩子节点,pright表示p的右孩子节点。

2,当p为null时,则f(p)为真。


由于f(p)需要返回p的深度和boolean值,将这两个值封装在一个对象里。

java代码如下,包括测试代码和核心代码

package AlgorithmTest;

/**
 * Created by dell on 2015/11/20.
 */
public class JudgeIsBalanceBinaryTreeUtil {
    public static void main(String[] args) {
        BinarySearchTree binarySearchTree = new BinarySearchTree();
        binarySearchTree.insertNode(4);
        binarySearchTree.insertNode(1);
        binarySearchTree.insertNode(5);//这个二叉排序树为二叉平衡术,因此判断应该为真
        if(JudgeBalanceBinaryTree(binarySearchTree.getRootNode())){
            System.out.println("is balanced binary tree");
        }else{
            System.out.println("not balanced binary tree");
        }
    }

    public static boolean JudgeBalanceBinaryTree(Node root){
        return isBalanceBinaryTree(root).isBalanced;
    }
    public static Result isBalanceBinaryTree(Node root){
        Result result = new Result();

        if (null == root){
            result.depth = 0;
            result.isBalanced = true;
            return result;
        }

        Result leftResult = isBalanceBinaryTree(root.nodeLeft);
        if (leftResult.isBalanced){
            Result rightResult = isBalanceBinaryTree(root.nodeRight);
            if (rightResult.isBalanced){
                int diff = leftResult.depth - leftResult.depth;
                if (diff <= 1 && diff >= -1){
                    result.isBalanced = true;
                    result.depth = 1 + (leftResult.depth > rightResult.depth ? leftResult.depth : rightResult.depth);
                    return result;
                }
            }
        }

        result.isBalanced = false;
        return result;
    }

    private static class Result{
        private boolean isBalanced;
        private int depth;

        public Result(){
            isBalanced = false;
            depth = 0;
        }
        public int getDepth() {
            return depth;
        }

        public void setDepth(int depth) {
            this.depth = depth;
        }

        public boolean isBalanced() {
            return isBalanced;
        }

        public void setIsBalanced(boolean isBalanced) {
            this.isBalanced = isBalanced;
        }
    }

}


       



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值