To find and insert binary search tree, it is more complicated to delete binary search tree. In the specific analysis can be deleted according to the node: 1, the left and right subtree are empty, 2, the left and right sub-tree is empty, 3, the left and right sub-trees are not empty case to consider.
The 3rd case is that the left and right sub-tree are not empty the situation is more complex, the deletion process can find the node to be deleted from the subsequent node, and the node to be deleted, and then the subsequent node of the tree access to the parent node of the node to be deleted.
Treenode* RemoveNode (treenode* root, int value) {//write your code here if (root = nullptr) return root; TreeNode *p, *q; p = root; Q = root;//p points to the node to be deleted, Q points to the parent node of the node to be deleted while (p) {if (value = = P-val) {break; }else if (value < P, val) {q = p; p = left; }else{q = p; p = p, right; }} if (p = = nullptr) return root; P is the leaf node if (p, left = = nullptr && p, right = = nullptr) {if (p = = q) { return nullptr; }else{if (left = = p) {q, left = nullptr; }else{Q-right = nullptr; } return root; }} There is an empty if (P-//p) in the left and right sub-tree left = = Nullptr | | P-right = = nullptr) {if (P-and left = nullptr) {if (p = = q) {return q right; }else{if (left = = p) {q, left = P, right; }else{Q-right = P-right; }}}else{if (p = = q) {return q, left ; }else{if (left = p) {q, left = P, left; }else{Q, right = P, left; }}} return root; The left and right subtrees of//p are non-empty if (P-and-right! = nullptr && P-, right! = nullptr) {TreeNode *fir = P right; TreeNode *sec = p; while (Fir-left! = nullptr) {SEc = Fir; Fir = Fir, left; } p, val = Fir, Val; if (P = = sec) {p, right = fir-right; }else{sec-left = fir-right; }} return root; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Delete a node of a binary lookup tree