Question:
Answer:
1. My code :
/**
* 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) return true;
else if(!isBalanced(root->left) || !isBalanced(root->right)) return false;
int height1 = height(root -> left);
int height2 = height(root -> right);
if (abs(height1-height2) <= 1) return true;
else return false;
}
int height(TreeNode *root){
if(!root) return 0;
else return max(height(root->left),height(root->right)) + 1;
}
};
2.Code online:
/******Better!*******/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(root == NULL) return true;
int val = GetBalance(root);
if(val ==-1) return false;
return true;
}
int GetBalance(TreeNode* node) {
if(node == NULL)
return 0;
int left = GetBalance(node->left);
if(left == -1) return -1;
int right = GetBalance(node->right);
if(right == -1) return -1;
if(left-right>1 || right-left>1)
return -1;
return left>right? left+1:right+1;
}
};
No comments:
Post a Comment