Balanced Binary Tree

来源:互联网 发布:阿尔法淘宝复制软件 编辑:程序博客网 时间:2024/05/16 06:21
public class Solution {public static void main(String[] args) {// TODO Auto-generated method stub}public boolean isBalanced(TreeNode root) {        if(root == null)        return true;        if((Math.abs(depth(root.left)-depth(root.right))>1))//左右子树深度大于1时,则是不平衡树        return false;        else        return isBalanced(root.left)&&isBalanced(root.right);//左右子树再进行递归    }public int depth(TreeNode node)//得到左右子树的最大深度{if(node == null)return 0;int leftdepth = depth(node.left);int rightdepth = depth(node.right);return Math.max(leftdepth, rightdepth)+1;}}class TreeNode {    int val;    TreeNode left;    TreeNode right;    TreeNode(int x)    {    val = x;    }}

0 0