Created
April 13, 2017 14:51
-
-
Save s4553711/6721152be81be4ecad445de41a542540 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
return check(root) != -1; | |
} | |
int check(TreeNode* node) { | |
if (node == NULL) return 0; | |
int levl = check(node->left); | |
int revl = check(node->right); | |
if (dis(levl - revl) > 1 || levl == -1 || revl == -1) { | |
return -1; | |
} | |
return (levl > revl ? levl : revl) + 1; | |
} | |
int dis(int i) { | |
return i < 0 ? -i : i; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment