首先是迭代求解,需要保留上一个结点
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root)
return new TreeNode(val);
TreeNode *pre=root,*pmove=root;
while(pmove)
{
pre=pmove;
pmove=pmove->val>val?pmove->left:pmove->right;
}
if(pre->val>val)
pre->left=new TreeNode(val);
else
pre->right=new TreeNode(val);
return root;
}
};
递归求解
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(!root)
return root=new TreeNode(val);
if(root->val>val)
root->left=insertIntoBST(root->left,val);
else
root->right=insertIntoBST(root->right,val);
return root;
}
};