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;
}
};