/**
* Definition for binary tree
* 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 == NULL) {
return true;
}
int height = 0;
return isBalancedHelper(root, height);
}
bool isBalancedHelper(TreeNode * root, int& height) {
if(root == NULL) {
return 0;
}
int left = 0;
if(root->left != NULL) {
if(!isBalancedHelper(root->left, left)) {
return false;
}
}
int right = 0;
if(root->right != NULL) {
if(!isBalancedHelper(root->right, right)) {
return false;
}
}
if(std::abs(left-right) > 1) {
return false;
}
height = std::max(left, right) + 1;
return true;
}
};
4/18/2014
Leetcode -- Balanced Binary Tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment