java 判断一个二叉树是不是平衡二叉树

来源:互联网 发布:淘宝网披肩女装 编辑:程序博客网 时间:2024/05/22 01:53

题目:

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. 

算法如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isBalanced(TreeNode root) {        if(root==null) return true;        if(root.left==null&&root.right==null)            return true;        if(root.left==null&&root.right!=null){            root = root.right;            if(root.left==null&&root.right==null)                return true;            else                return false;        }        if(root.right==null&&root.left!=null){            root = root.left;            if(root.left==null&&root.right==null)                return true;            else                return false;        }        if(root.right!=null&&root.left!=null){            boolean flag1 = isBalanced(root.right);            boolean flag2 = isBalanced(root.left);            if(!(flag1&&flag2))                return false;            else{                int x = Math.abs(maxDepth(root.left)-maxDepth(root.right));                if(x>1){                    return false;                }else{                    return true;                }            }        }        return true;    }    public int maxDepth(TreeNode root){        if(root==null){            return 0;        }        if(root.left==null&&root.right==null){            return 1;        }        if(root.left==null){            return maxDepth(root.right)+1;        }        if(root.right==null){            return maxDepth(root.left)+1;        }        if(root.left!=null&&root.right!=null){            return max(maxDepth(root.left),maxDepth(root.right))+1;        }        return 0;    }    public int max(int a,int b){        return a>b?a:b;    }}
1 0