LeetCode110:Balanced Binary Tree

来源:互联网 发布:2017机顶盒直播软件 编辑:程序博客网 时间:2024/06/05 12:05

这里写图片描述

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int getDepth(TreeNode root, int curDepth){        ////如果为空 则返回当前的深度        if(root==null) return curDepth;        //返回子树中最大的深度        return Math.max(getDepth(root.left,curDepth+1),getDepth(root.right,curDepth+1));    }    public boolean isBalanced(TreeNode root) {        //树为空        if(root==null) return true;        //左子树的最大深度        int left = getDepth(root.left,1);        //右子树的最大深度        int right = getDepth(root.right,1);        //深度之差不能大于1 否则不平衡        if(Math.abs(left-right)>1){            return false;        }else{            //左子树和右子树是否为平衡树            return isBalanced(root.left) && isBalanced(root.right);        }    }}
0 0
原创粉丝点击