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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/
9 20
/
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/
2 2
/
3 3
/
4 4
Return false.
Approach #1: C++.[recursive]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
int left = helper(root->left);
int right = helper(root->right);
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
private:
int helper(TreeNode* root) {
if (root == nullptr) return 0;
return max(helper(root->left), helper(root->right)) + 1;
}
};
Approach #2: Java.[DFS]
/**
* 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 root) {
if (root == null) return 0;
int left = dfs(root.left);
if (left == -1) return -1;
int right = dfs(root.right);
if (right == -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}
Approach #3: Python.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return abs(self.solve(root.left) - self.solve(root.right)) and self.isBalanced(root.left) and self.isBalanced(root.right)
def solve(self, root):
if not root:
return 0
return max(self.solve(root.left), self.solve(root.right)) + 1