什么是搜索树,不说了,《数据结构》,比较基础,可以百度等。
可以直接用的,可以参考下,我代码风格可能稍微有些繁琐。
默认树节点的结构是一个val,一个left指针,一个right指针。
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root==NULL){
root=new TreeNode(val);
return root;
}
//it has to be SOME node with at least one NULL pointer.
//but it has not to be THE node.
if(root->right==NULL||root->left==NULL){
//check if it is the node we want to insert.
if(root->left&&root->right==NULL){
if(val>root->val){
TreeNode *t=new TreeNode(val);
root->right=t;
return root;
}
else insertIntoBST(root->left,val);
}
else if(root->left==NULL&&root->right){
if(val<root->val){
TreeNode *t=new TreeNode(val);
root->left=t;
return root;
}
else insertIntoBST(root->right,val);
}
else{
TreeNode *t=new TreeNode(val);
if(val<root->val) root->left=t;
else root->right=t;
return root;
}
}
else{
if(val<root->val) insertIntoBST(root->left,val);
else if(val>root->val) insertIntoBST(root->right,val);
return root;
}
return root;
}