Implementation of binary sorting tree (partial)
1. Write the pseudo code of SearchBST (T, key) and InsertBST (T, key)
-
SearchBST pseudocode :
void SearchBST(T,key){ if(T为空||T==key) return T; if(T>key) SearchBST(T->lchild,key); else SearchBST(T->rchild,key); }
-
InsertBST pseudocode :
void InsertBST(T,key){ if(T为空){ T=new Node; T=key; T->lchild=NULL; T->rchild=NULL; return 1; }else if(T==key) return 0; else if(T>key) InsertBST(T->lchild,key); else InsertBST(T->rchild,key); }
2. Write the pseudo code of CreateBST (T) to create a BST tree from the console input. Finally use code to achieve. Use "50 30 80 20 40 90 10 25 35 85 23 88" to create a BST and output the BST in sequence
-
CreateBST pseudocode :
void CreateBST(T){ T=new Node; T->lchild=NULL; T->rchild=NULL; //输入key if(T不空) T=key; while(key!=0){ //输入key if(T不空){ InsertBST(T,key); } } }
-
Create a BST tree:
-
Data type definition:
typedef struct BSTNode { int data; struct BSTNode* lchild, * rchild; }*BSTree;
-
SearchBST function:
BSTree SearchBST(BSTree T, int key) { if (T == NULL || T->data == key) return T; if (T->data > key) return SearchBST(T->lchild, key); else return SearchBST(T->rchild, key); }
-
InsertBST function:
void InsertBST(BSTree T, int key) { if (T == NULL){ T = new BSTNode; T->data = key; T->lchild = NULL; T->rchild = NULL; return; } else if (T->data == key) return; else if (T->data > key) return InsertBST(T->lchild, key); else return InsertBST(T->rchild, key); }
-
CreateBST function:
void CreateBST(BSTree T) { T = new BSTNode; T->lchild = NULL; T->rchild = NULL; int key; cin >> key; if (T != NULL) T->data = key; while (key != 0) { cin >> key; if (T != NULL) { InsertBST(T, key); } } }
-
In-order traversal:
void InOrder(BSTree T) { if (T != NULL) { InOrder(T->lchild); cout << T->data<<" "; InOrder(T->rchild); } }
-
main function:
void main() { BSTree T; T = new BSTNode; int key; CreateBST(T); cout << "中序遍历结果为:" << endl; InOrder(T); cin >> key; SearchBST(T, key); InsertBST(T, key); InOrder(T); }
-
3. Write the pseudo code of DeleteBST (T, key) to delete the key from T.
Matters needing attention and points:
To delete the keyword key, you must first determine the location of the node where the key is located: ①leaf node ②only left or right subtree nodes ③nodes that have left and right subtrees
①Leaf node: delete the key directly after finding it;
②Only the left or right subtree node: point rchild / lchild of T's parent node to rchild / lchild of T, and move the left and right subtree nodes upward;
③ Nodes in both the left and right subtrees: replace the T node with the direct precursor of T or the rightmost node of the right subtree.