110. Balanced Binary Tree - jiejackyzhang/leetcode-note GitHub Wiki
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.
Tree类题目。
一棵二叉树是height-balanced的条件是:
- 它的左右子树高度差不超过1;
- 它的左右子树也都是height-balanced的。
因此问题转换为一个recursive problem,关键点在于求出树的height。 求树的height也可以用recursion来解
/**
* 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 (Math.abs(height(root.left) - height(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode node) {
if(node == null) return 0;
return Math.max(height(node.left), height(node.right)) + 1;
}
}
上面的方法虽然比较直观,但是每次调用isBalanced方法都要将左右子树的height计算一遍,做了很多重复的工作。 可以只遍历一遍tree,计算height的同时返回是否balanced。 本质上是post-order traversal。
/**
* 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) {
return root == null || helper(root) != -1;
}
private int helper(TreeNode node) {
if(node.left == null && node.right == null) return 1;
int lh = 0, rh = 0;
if(node.left != null) lh = helper(node.left);
if(node.right != null) rh = helper(node.right);
if(lh == -1 || rh == -1) return -1;
if(Math.abs(lh - rh) > 1) return -1;
return Math.max(lh, rh) + 1;
}
}