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.
一刷
題解:
判斷一個(gè)樹是不是balanced tree. 首先要知道balanced tree的定義:一個(gè)樹中的同一個(gè)level的子樹的長(zhǎng)度差不會(huì)超過(guò)1,所以只算root的左右子樹的高度差是不夠的啥刻。同樣的玷犹,我們也可以思考怎么樣讓循環(huán)提前終止炉爆,當(dāng)不滿足要求時(shí)肴熏。
/**
* 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的函數(shù)間接解钥平,并且注意利用條件提前結(jié)束
/**
* 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);
}
}