解法一:递归
/**
* 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) {
if(root == NULL){
return new TreeNode(val);
}
if(val < root->val){
root->left = insertIntoBST(root->left, val);
}
else{
root->right = insertIntoBST(root->right, val);
}
return root;
}
};
解法二:迭代
!!!也很好理解,要注意,当找到合适的位置时,要及时返回。
/**
* 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) {
if(root == NULL) return new TreeNode(val);
TreeNode* tmp = root;
while(tmp){
if(tmp->val > val){
if(tmp->left == NULL){
tmp->left = new TreeNode(val);
return root;
}
tmp = tmp->left;
}
else{
if(tmp->right == NULL){
tmp->right = new TreeNode(val);
return root;
}
tmp = tmp->right;
}
}
return root;
}
};