/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: pair<bool , int> search(TreeNode* root){ if(root == NULL) return make_pair(true , 0); pair<bool , int> left = search(root -> left); pair<bool , int> right = search(root -> right); if( left.first == false || right.first == false) return make_pair(false , -1); int depL = left.second; int depR = right.second; if(abs(depL - depR) > 1) return make_pair(false , -1); return make_pair(true , max(depL , depR) + 1); } bool isBalanced(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. pair<bool , int> ans = search(root); return ans.first; } };
by 1957