110. Balanced Binary Tree

来源:互联网 发布:ipad应用网络连接失败 编辑:程序博客网 时间:2024/05/21 17:31

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.



判断是否是平衡二叉树

     深度相差一:

1.所有子树的深度都相差不超过一 

2.求子树的深度


public class Solution {    /**     * @param root: The root of binary tree.     * @return: True if this Binary tree is Balanced, or false.     */    public boolean isBalanced(TreeNode root) {        if(root==null) return true;                int left=depth(root.left);        int right=depth(root.right);                return Math.abs(left-right)<=1&&isBalanced(root.left)&&isBalanced(root.right);    }    public int depth(TreeNode root){        if(root==null) return 0;        return Math.max(depth(root.left),depth(root.right))+1;            }   }


0 0
原创粉丝点击