110. Balanced Binary Tree

来源:互联网 发布:阿里云虚拟主机 php7 编辑:程序博客网 时间:2024/06/06 06:52

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.

Balanced Binary Tree的定义是左右子树的高度差小于等于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;        }        return subTree(root) != -1;    }    public int subTree (TreeNode root) {        if (root == null) {            return 0;        }        int left = subTree(root.left);        int right = subTree(root.right);        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {            return -1;        }        return Math.max(left, right) + 1;    }}

0 0
原创粉丝点击