1. 程式人生 > >**Leetcode 450. Delete Node in a BST

**Leetcode 450. Delete Node in a BST

不錯的題 有一些細節需要注意

/**
 * 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* dfs(TreeNode *root, int k, int &get) {
        if (!root || get) return root;
        if (k == root->val) {
            get = 1;
            TreeNode * right = root->left, *pre = NULL;
            if (!right) return root->right;
            while (right->right) pre = right, right = right -> right;
            if (right == root->left) {
                right ->right = root->right;
                return right;
            } else {
                pre->right = right->left;
                right->left = root->left;
                right->right = root->right;
                return right;
            }
        }
        
        root->left = dfs(root->left, k, get);
        root->right = dfs(root->right, k, get);
        return root;
    }
    
    TreeNode* deleteNode(TreeNode* root, int key) {
        int get = 0;
        return dfs(root, key, get);
    }
};