C++ recursive O(h) time O(1) space

  • 0
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (root==NULL) return NULL;
        if (key < root->val) 
            root->left = deleteNode(root->left, key);
        else if (key > root->val)
            root->right= deleteNode(root->right, key);
        else {
            if (!root->right) {
                TreeNode *p = root->left;
                delete root;
                return p;
            else {
                TreeNode *p = root->right;
                while (p->left) p=p->left;
                swap(root->val, p->val);
                root->right=deleteNode(root->right, key);
        return root;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.