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 tree. 首先要知道balanced tree的定义:一个树中的同一个level的子树的长度差不会超过1,所以只算root的左右子树的高度差是不够的。同样的,我们也可以思考怎么样让循环提前终止,当不满足要求时。
/**
* 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 height(root)!=-1;
}
private int height(TreeNode root){
if(root == null) return 0;
int lh = height(root.left);
if(lh == -1) return -1;
int rh = height(root.right);
if(rh == -1) return -1;
if(Math.abs(lh-rh)>1) return -1;
return Math.max(lh, rh)+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 height(root)!=-1;
}
private int height(TreeNode root){
if(root == null) return 0;
int lh = height(root.left);
int rh = height(root.right);
if(lh == -1 || rh == -1 || Math.abs(lh-rh)>1) return -1;
return 1 + Math.max(lh, rh);
}
}
三刷
利用求height的函数间接解,并且注意利用条件提前结束
/**
* 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 height(root)!=-1;
}
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(left == -1 || right == -1 || Math.abs(left-right)>1) return -1;
return 1 + Math.max(left, right);
}
}