leetcode

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

0814.cpp (930B)


      1 class Solution {
      2   public:
      3     TreeNode *pruneTree(TreeNode *root) {
      4         TreeNode dummy(1, root, nullptr);
      5         unordered_set<TreeNode *> has;
      6         stack<TreeNode *> st;
      7         st.push(&dummy);
      8         while (!st.empty()) {
      9             TreeNode *root = st.top();
     10             if (!root) {
     11                 st.pop();
     12                 root = st.top(), st.pop();
     13                 if (has.count(root->left))
     14                     has.insert(root);
     15                 else
     16                     root->left = nullptr;
     17 
     18                 if (has.count(root->right))
     19                     has.insert(root);
     20                 else
     21                     root->right = nullptr;
     22 
     23                 if (root->val == 1) has.insert(root);
     24                 continue;
     25             }
     26             st.push(nullptr);
     27             if (root->left) st.push(root->left);
     28             if (root->right) st.push(root->right);
     29         }
     30         return dummy.left;
     31     }
     32 };