knakul853

Untitled

Jul 22nd, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. /**
  2.  knakul853
  3.  */
  4. class Solution {
  5. public:
  6.     bool isBalanced(TreeNode* root) {
  7.        
  8.         if(!root)return 1;
  9.        
  10.         int lh = ht(root->left);
  11.         int rh = ht(root->right);
  12.        
  13.         bool res = true;
  14.         res&=abs(lh - rh)<=1;
  15.         res&=isBalanced(root->left);
  16.         res&=isBalanced(root->right);
  17.          return res;
  18.        
  19.        
  20.        
  21.     }
  22.    
  23.     private:
  24.     int ht(TreeNode* node)
  25.     {
  26.         if(!node)return 0;
  27.         return 1+max(ht(node->left),ht(node->right));
  28.     }
  29. };
  30.  
  31. //https://leetcode.com/problems/balanced-binary-tree/discuss/35691/The-bottom-up-O(N)-solution-would-be-better
  32. class solution {
  33. public:
  34. int dfsHeight (TreeNode *root) {
  35.         if (root == NULL) return 0;
  36.        
  37.         int leftHeight = dfsHeight (root -> left);
  38.         if (leftHeight == -1) return -1;
  39.         int rightHeight = dfsHeight (root -> right);
  40.         if (rightHeight == -1) return -1;
  41.        
  42.         if (abs(leftHeight - rightHeight) > 1)  return -1;
  43.         return max (leftHeight, rightHeight) + 1;
  44.     }
  45.     bool isBalanced(TreeNode *root) {
  46.         return dfsHeight (root) != -1;
  47.     }
  48. };
Add Comment
Please, Sign In to add comment