← Home

450. Delete Node in a BST

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
450

Let's make this one less mysterious. For 450. Delete Node in a BST, the solution in this repository is mainly a two pointers solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are deleteNode.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 36 ms, faster than 69.49% of C++ online submissions for Delete Node in a BST.
02//Memory Usage: 15.3 MB, less than 55.49% of C++ online submissions for Delete Node in a BST.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    TreeNode* deleteNode(TreeNode* root, int key) {
17        if(!root) return root;
18
19        TreeNode *par = root, *cur = root;
20
21        while(cur && cur->val != key){
22            if(key < cur->val){
23                par = cur;
24                cur = cur->left;
25            }else{
26                //key > cur->val
27                par = cur;
28                cur = cur->right;
29            }
30        }
31
32        //cannot find key in tree
33        if(!cur) return root;
34        
35        if(!cur->left && !cur->right){
36            if(cur == root) return nullptr;
37            if(par->left == cur) par->left = nullptr;
38            else par->right = nullptr;
39        }else if(cur->left){
40            //predecessor of deleted node
41            TreeNode *pred = cur->left;
42            //parent of predecessor
43            par = pred;
44            while(pred->right){
45                par = pred;
46                pred = pred->right;
47            }
48            cur->val = pred->val;
49            /*
50            pred->right is always empty,
51            when predecessor is the left child of the node to be deleted,
52            we move pred's left subtree one level up
53            (set left subtree's parent as cur),
54            if not, pred is then it's parent's right child,
55            here we also move pred's left subtree one level up
56            (set left subtree's parent as par)
57            */
58            if(cur->left == pred) cur->left = pred->left; 
59            else par->right = pred->left;
60        }else{
61            TreeNode *succ = cur->right;
62            par = succ;
63            while(succ->left){
64                par = succ;
65                succ = succ->left;
66            }
67            cur->val = succ->val;
68            if(cur->right == succ) cur->right = succ->right; 
69            else par->left = succ->right;
70        }
71
72        return root;
73    }
74};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.