迭代
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root)
return new TreeNode(val);
TreeNode*cur=root;
while(cur)
{
if(val<cur->val)
{
if(cur->left)
cur=cur->left;
else
{
cur->left=new TreeNode(val);
break;
}
}
else if(val>cur->val)
{
if(cur->right)
cur=cur->right;
else
{
cur->right=new TreeNode(val);
break;
}
}
}
return root;
}
};
递归
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root) return new TreeNode(val);
else if(val>root->val) root->right=insertIntoBST(root->right,val);
else root->left=insertIntoBST(root->left,val);
return root;
}
};
END