Balanced Binary Tree
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.
*/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.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int abs(int value){
if(value<0) return (-1)*value;
return value;
}
int height(TreeNode *node, bool & isBalance){
if(node==NULL) return 0;
if(((abs(height(node->left,isBalance)-height(node->right, isBalance)))>1) && isBalance==true){
isBalance = false;
}
if (isBalance) return max(height(node->left, isBalance), height(node->right, isBalance))+1;
else return 0;
}
bool isBalanced(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool isBalance = true;
height(root, isBalance);
return isBalance;
}
};
No comments:
Post a Comment