leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0110.cpp (749B)


      1 class Solution {
      2   public:
      3     bool isBalanced(TreeNode *root) {
      4         if (!root) return true;
      5         stack<TreeNode *> st;
      6         st.push(root);
      7         while (!st.empty()) {
      8             TreeNode *root = st.top();
      9             if (root == nullptr) {
     10                 st.pop(), root = st.top(), st.pop();
     11                 int left = root->left ? root->left->val : 0;
     12                 int right = root->right ? root->right->val : 0;
     13                 if (abs(right - left) > 1) return false;
     14                 root->val = max(left, right) + 1;
     15                 continue;
     16             }
     17             st.push(nullptr);
     18             if (root->left) st.push(root->left);
     19             if (root->right) st.push(root->right);
     20         }
     21         return true;
     22     }
     23 };