701. 二叉搜索树中的插入操作 二叉树

给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。

注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

生成新指针使用return new TreeNode(val)

递归版

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) {
            return new TreeNode(val);
        }
        if (val > root->val) {
            root->right = insertIntoBST(root->right, val);
        }
        else {
            root->left = insertIntoBST(root->left, val);
        }
        return root;
    }
};

迭代版

class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) {
            return new TreeNode(val);
        }

        TreeNode* pre = root;
        TreeNode* p = root;

        while (p != nullptr) {
            pre = p;
            p = val < p->val ? p->left : p->right;
        }

        if (val > pre->val) {
            pre->right = new TreeNode(val);
        }
        else {
            pre->left = new TreeNode(val);
        }

        return root;

    }
};
原文地址:https://www.cnblogs.com/xgbt/p/13752930.html