27 lines
554 B
C++
27 lines
554 B
C++
#include "s0701_insert_into_a_binary_search_tree.hpp"
|
|
|
|
TreeNode* S0701::insertIntoBST(TreeNode* root, int val) {
|
|
TreeNode *cur = root;
|
|
if (root == nullptr) {
|
|
return new TreeNode(val);
|
|
}
|
|
while (true) {
|
|
if (val < cur->val) {
|
|
if (cur->left == nullptr) {
|
|
cur->left = new TreeNode(val);
|
|
break;
|
|
} else {
|
|
cur = cur->left;
|
|
}
|
|
} else {
|
|
if (cur->right == nullptr) {
|
|
cur->right = new TreeNode(val);
|
|
break;
|
|
} else {
|
|
cur = cur->right;
|
|
}
|
|
}
|
|
}
|
|
return root;
|
|
}
|