手写BST插入查找删除

来源:互联网 发布:番茄计时器 windows 编辑:程序博客网 时间:2024/05/09 21:43
binary search\sort\find tree operations


status InsertNode(Node* root, data x, Node* father){if(root==NULL){if(father==NULL)Tree empty;else{if(x<father->data){father->left=new Node//inital left right NULLfather->left->data=x;return  success;}else if(father->data<x){father->right=new Node;//inital left right NULLfather->right->data=x;return succes;}else{return failure, have same data in BST//Hash also not allowed same data, but other such as array allow}}}if(x<root->data) InsertNode(root->left,x); //imitate big god fawks's code style : )else if(root->data<x) InsertNode(root->right,x);elsereturn falure, have same data in BST;}

后来发现,根本不需要father, 会出现上面的原因是我总以为指针为空,指针变量也不能在赋值了。有个错误理解,指针变量是一个变量,他的值为空,现在可以让他指向其他的地方,例如申请一个堆空间,他的值就是这个新的空间的地址值。


status InsertNode(Node* root, data x){if(root==NULL){root=new Node;//assume initial left right NULLroot->data=x;}if(x<root->data) InsertNode(root->left,x); //imitate big god fawks's code : )else if(root->data<x) InsertNode(root->right,x);elsereturn falure, have same data in BST;}





Node* FindNode(Node* root, data x, Node* father)//use father for delete recall{if(root==NULL) return NULL;if(x<root->data) FindNode(root->left, x,root);else if(root0>data<x) FindNode(root->right,x,root);elsereturn root;}

status DeleteNode(Node* root, data x){Node* parent=NULL;Node* p=FindNode(root,x,parent);if(p==NULL)return failure, can not found x;if(parent==NULL)//BST only has a rootreturn success root==NULL;//set BST as NULLif(p==parent->left){if(p-left!=NULL){move p's right child as p's leftchild's rightdownmost node's right child parent->left=p->left;}else if(p->right!=NULL){move p's left child as p's rightchild's leftdownmost node's left child;parent->left=p->right;}else// all null{parent->left==NULL;}delete p;}if(p==parent->right){follow left part;}return sucess;}




总结指针bug就是 每次访问left right,都要考虑是否p为空,如果有空就另外处理,否则NULL访问left right 程序就crash了。
0 0