码迷,mamicode.com
首页 > 其他好文 > 详细

平衡二叉树

时间:2016-06-24 15:24:42      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

题目

输入一棵二叉树,判断该二叉树是否是平衡二叉树

解题

平衡二叉树:每个节点左右子树的高度差只能是:-1、0、1
判断每个节点左右子树高度是否满足上面条件

import java.util.LinkedList;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root ==null)
            return true;
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        int diff = left - right;
        if(diff>=-1 && diff <=1){
            return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
        }else{
            return false;
        }
    }
    public int TreeDepth(TreeNode pRoot){
        if(pRoot ==null)
            return 0;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(pRoot);
        int depth = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            depth++;
            while(size-- >0){
                TreeNode node = queue.poll();
                if(node.left!=null)
                    queue.add(node.left);
                if(node.right!=null)
                    queue.add(node.right);
            }
        }
        return depth;
    }

}

讨论中看到下面的程序,利用后序遍历,先求出左右子树的高度,判断条件,满足继续,不满足停止,这里没有严格的求每个节点的高度

import java.util.LinkedList;
public class Solution {
    private boolean isBalanced=true;
    public boolean IsBalanced_Solution(TreeNode root) {

        getDepth(root);
        return isBalanced;
    }
    public int getDepth(TreeNode root){
        if(root==null)
            return 0;

        int left=getDepth(root.left);
        int right=getDepth(root.right);

        if(Math.abs(left-right)>1){
            isBalanced=false;
            root =null;
        }
        return right>left ?right+1:left+1;

    }

}

平衡二叉树

标签:

原文地址:http://blog.csdn.net/qunxingvip/article/details/51747720

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!