标签:
在二叉搜索树中查找一个数,如果存在,则从树中删除。
struct Node { Node* left; Node* right; int data; }; void findAndDel(Node*& head, int k) { if (!head) return; Node* node = head; Node* vnode = new Node; vnode->left = vnode->right = head; Node* pnode = vnode; // find node while (node) { if (node->data > k) { if (node->left == NULL) return; else { pnode = node; node = node ->left; } } else if (node->data < k) { if (node->right == NULL) return; else { pnode = node; node = node->left; } } else break; } // found if (node->left == NULL) { if (pnode->right == node) pnode->right = node->right; else pnode->left = node->right; delete node; } else if (node->right == NULL) { if (pnode->right == node) pnode->right = node->left; else pnode->left = node->left; delete node; } else { Node* leftBiggest = node->left; Node* leftBiggestP = node; while (leftBiggest->right != NULL) { leftBiggestP = leftBiggest; leftBiggest = leftBiggest->right; } node->data = leftBiggest->data; if (leftBiggestP->left == leftBiggest) leftBiggestP->left = leftBiggest->left; else leftBiggestP->right = leftBiggest->left; delete leftBiggest; } head = vnode->right; delete vnode; }
标签:
原文地址:http://www.cnblogs.com/litao-tech/p/4376742.html