A very modularized c++ solution (beats 98%)


  • 1
    V

    class Solution {
    public:

    TreeNode*& findNode(TreeNode*& root, int key) {
        if ( !root or root->val == key ) return root;
        else return ( root->val > key? findNode( root->left, key ) : findNode( root->right, key ) );
    }
    
    bool insertNode(TreeNode*& root, TreeNode* node) {
        if ( !root ) {
            root = node;
            return true;
        }
        if ( !node ) return true;
        if ( root->val < node->val ) return insertNode( root->right, node );
        else if ( root->val > node->val ) return insertNode( root->left, node );
        else return false;
    }
    
    TreeNode* deleteNode(TreeNode* root, int key) {
        TreeNode*& node = findNode( root, key );
        if ( !node ) return root;
        TreeNode* left = node->left;
        TreeNode* right = node->right;
        node = NULL;
        insertNode( root, left );
        insertNode( root, right );
        return root;
    }
    

    };


Log in to reply
 

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