1 bool Insert(const K& key) 2 { 3 if (_root == NULL) 4 { 5 _root = new Node(key); 6 return true; 7 } 8 Node* parent=NULL; 9 Node* pcur = _root; 10 while (pcur) 11 { 12 if (pcur->_key == key) //有key節點,則不再插入 13 return false; 14 if (pcur->_key > key) 15 { 16 parent = pcur; 17 pcur = pcur->_left; 18 } 19 else if (pcur->_key < key) 20 { 21 parent = pcur; 22 pcur = pcur->_right; 23 } 24 } 25 if (parent->_key < key) 26 parent->_right = new Node(key); 27 else 28 parent->_left = new Node(key); 29 return true; 30 }
2、二叉搜索樹的刪除操作 bool Remove(const K& key)
1 bool Remove(const K& key) 2 { 3 assert(_root); 4 Node* parent = NULL; 5 Node* pcur = _root; 6 Node* del = pcur; 7 while (pcur != NULL && pcur->_key != key) 8 { 9 if (pcur->_key > key) 10 { 11 parent = pcur; 12 pcur = pcur->_left; 13 } 14 else if (pcur->_key < key) 15 { 16 parent = pcur; 17 pcur = pcur->_right; 18 } 19 } 20 if (pcur == NULL) 21 return false; 22 if (pcur->_left == NULL) //只有右孩子 23 { 24 //如果pcur就是根節點的話,讓根節點指向根的右 25 if (pcur == _root) 26 _root = pcur->_right; 27 else if (pcur == parent->_left) 28 { 29 parent->_left = pcur->_right; 30 } 31 else 32 { 33 parent->_right = pcur->_right; 34 } 35 del = pcur; 36 } 37 else if (pcur->_right == NULL) //只有左孩子 38 { 39 //如果是根節點,讓根節點指向根的左 40 if (pcur == _root) 41 _root = pcur->_left; 42 else if (parent->_left == pcur) 43 { 44 parent->_left = pcur->_left; 45 } 46 else 47 parent->_right = pcur->_left; 48 del = pcur; 49 } 50 //pcur左右孩子都不為空 51 else 52 { 53 //找到節點右子樹的最左節點 54 Node* left = pcur->_right; 55 parent = pcur; 56 while (left->_left) 57 { 58 parent=left; 59 left = left->_left; 60 } 61 del = left; 62 pcur->_key = left->_key; //交換節點的值 63 if (parent->_left == left) 64 { 65 parent->_left = left->_right; 66 } 67 else 68 { 69 parent->_right = left->_right; 70 } 71 72 } 73 delete del; 74 return true; 75 }