leetcode

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

0450.cpp (918B)


      1 class Solution {
      2     TreeNode *deleteRoot(TreeNode *root) {
      3         if (!root) return nullptr;
      4         if (!root->left) return root->right;
      5         if (!root->right) return root->left;
      6 
      7         TreeNode *next = root->right;
      8         TreeNode *pre = nullptr;
      9         while (next->left) {
     10             pre = next;
     11             next = next->left;
     12         }
     13         next->left = root->left;
     14         if (root->right != next) {
     15             pre->left = next->right;
     16             next->right = root->right;
     17         }
     18         return next;
     19     }
     20 
     21   public:
     22     TreeNode *deleteNode(TreeNode *root, int key) {
     23         TreeNode *cur = root, *pre = nullptr;
     24         while (cur && cur->val != key) {
     25             pre = cur;
     26             cur = key < cur->val ? cur->left : cur->right;
     27         }
     28 
     29         if (!pre) return deleteRoot(cur);
     30         (pre->left == cur ? pre->left : pre->right) = deleteRoot(cur);
     31         return root;
     32     }
     33 };