# 450. Delete Node in a BST

## 1.問題

![](/files/-LKMYEbRpOImKhu9P4IZ)

## 2.想法

* 當左右子都存在時, 取右子樹的最左子移到root, 並且刪除右子樹

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (root == NULL ) {
            return NULL;
        }
        
        if (root->val < key) {
            //traverse
            root->right = deleteNode(root->right, key);
        } else if (root->val > key) {
            //traverse
            root->left = deleteNode(root->left, key);
        } else {
            //Remove
            if (root->left == NULL &&
                root->right == NULL) {
                return NULL;
            } else if (root->left == NULL) {
                return root->right;
            } else if (root->right == NULL) {
                return root->left;
            } else {
                TreeNode *tmp = root->right;
                while (tmp->left) {
                    tmp = tmp->left;
                }
                root->val = tmp->val;
                root->right = deleteNode(root->right, root->val);
            }
        }
        
        return root;
    }
};
```

## 4.Performance

![](/files/-LKMYRfkw0u_uYD7A1sV)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/450.-delete-node-in-a-bst.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
