文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Iterative
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode* insert = new TreeNode(val);
if(!root) {
root = insert;
return root;
}
TreeNode* current = root;
TreeNode* pre = NULL;
while(current) {
pre = current;
if(current->val > val) {
current = current->left;
}
else {
current = current->right;
}
}
if(pre->val > val) {
pre->left = insert;
}
else {
pre->right = insert;
}
return root;
}
};
- Recursive
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode* insert = new TreeNode(val);
if(!root) {
root = insert;
return root;
}
insertNodeIntoBST(root, val);
return root;
}
void insertNodeIntoBST(TreeNode* root, int val) {
if(root->val > val) {
if(!root->left) {
root->left = new TreeNode(val);
}
else {
insertNodeIntoBST(root->left, val);
}
}
else {
if(!root->right) {
root->right = new TreeNode(val);
}
else {
insertNodeIntoBST(root->right, val);
}
}
}
};