Is there any way to delete an element from the BST without using recursion and without using a second function?

Viewed 71

I was going through a problem to delete an element from the BST, and I wrote the following program:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* r, int k) {
        if(r==0)
            return 0;
        if(r->val<k)
        {
            r->right=deleteNode(r->right,k);
            return r;
        }
        else if(r->val>k)
        {
            r->left=deleteNode(r->left,k);
            return r;
        }
        if(r->left==0)
            return r->right;
        if(r->right==0)
            return r->left;        
        TreeNode *p=r->right;
        while(p->left)
            p=p->left;
        p->left=r->left;
        return r->right;
    }
};

The main problem that I want to solve is to include the last while loop as the part of recursion.

Note that I do not want to use any other function, like isMin(), etc.

0 Answers
Related