Problem
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.
Solution
1.top-down的遍历方式,时间复杂度为O(nlogn)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return Math.abs(depth(root.left)-depth(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right);
}
private int depth(TreeNode node){
if(node==null) return 0;
return Math.max(depth(node.left),depth(node.right))+1;
}
}
2.bottom-up方法,时间复杂度O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return DFS(root)!=-1;
}
private int DFS(TreeNode node){
if(node==null)return 0;
int depthLeft = DFS(node.left);
if(depthLeft == -1) return -1;
int depthRight = DFS(node.right);
if(depthRight == -1) return -1;
if(Math.abs(depthLeft-depthRight)>1)return -1;
return Math.max(depthLeft,depthRight)+1;
}
}