迭代法
/**
* 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 == nullptr){
TreeNode* node = new TreeNode(val);
return node;
}
TreeNode* p = root;
TreeNode* parent;
bool isleft = false;
while (p){
isleft = false;
parent = p;
if (p->val > val){
isleft = true;
p = p->left;
}else if(p->val < val){
p = p->right;
}
}
if (parent && isleft){
parent->left = new TreeNode(val);
}else if (parent && !isleft){
parent->right = new TreeNode(val);
}
return root;
}
};
递归法
/**
* 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 == nullptr){
root = new TreeNode(val);
return root;
}
if (root->val > val){
root->left = insertIntoBST(root->left, val);
}else if(root->val < val){
root->right = insertIntoBST(root->right, val);
}
return root;
}
};