/**
 * 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;
    }
};

 

相关文章:

  • 2021-11-25
  • 2021-10-24
  • 2021-08-27
  • 2022-03-08
  • 2021-11-06
  • 2021-12-22
  • 2021-06-26
猜你喜欢
  • 2021-09-10
  • 2022-02-04
  • 2022-02-04
  • 2021-10-11
  • 2022-02-18
  • 2021-12-01
  • 2021-05-29
相关资源
相似解决方案