Leetcode|BST修改与构造|701. BST的插入操作

2021-09-18 15:55:16 浏览数 (1)

1 递归

代码语言:javascript复制
/**
 * 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* insertIntoBST(TreeNode* root, int val) {
        if (!root) return new TreeNode(val);
        if (root->val == val) return root;
        if (val < root->val)
            root->left = insertIntoBST(root->left, val);
        if (val > root->val)
            root->right = insertIntoBST(root->right, val);
        return root;
    }
};

2 迭代法

代码语言:javascript复制
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (!root) return new TreeNode(val);
        auto node = root;
        while (true) {
            if (node->val == val) break;
            if (val < node->val) {  // 应该插入到左子树
                if (node->left)
                    node = node->left;
                else {
                    node->left = new TreeNode(val);
                    break;
                }
            } else {                // 应该插入到右子树
                if (node->right)
                    node = node->right;
                else {
                    node->right = new TreeNode(val);
                    break;
                }
            }
        }
       return root;
    }
};

0 人点赞