Leetcode 784 Solution

This article provides solution to leetcode question 784 (insert-into-a-binary-search-tree)

https://leetcode.com/problems/insert-into-a-binary-search-tree

Solution

/**
 * 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* insertIntoBST(TreeNode* root, int val) {
        TreeNode dummyRoot(-2147483648);
        dummyRoot.right = root;

        TreeNode* curr = root;
        TreeNode* last = &dummyRoot;

        while (curr)
        {
            if (curr->val > val)
            {
                last = curr;
                curr = curr->left;
            }
            else if (curr->val < val)
            {
                last = curr;
                curr = curr->right;
            }
        }

        if (val < last->val)
            last->left = new TreeNode(val);
        else
            last->right = new TreeNode(val);

        return dummyRoot.right;
    }
};