Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- private:
- int treeHeight(TreeNode * root, bool& balanced) {
- if (root == NULL) { balanced = true; return 0; }
- bool left, right;
- int left_height = treeHeight(root->left, left) + 1;
- int right_height = treeHeight(root->right, right) + 1;
- balanced = left && right;
- if (!balanced) return 0;
- int result = left_height - right_height;
- balanced = (result >= -1 && result <= 1);
- return max(left_height, right_height);
- }
- public:
- bool isBalanced(TreeNode *root) {
- if (root == NULL) return true;
- bool left, right;
- int result = treeHeight(root->left, left) - treeHeight(root->right, right);
- return (left&&right)&&(result >= -1 && result <= 1);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement