C++ 中的二叉搜索树节点删除
假设我们有一个二叉搜索树。我们将取一个键 k,并且我们必须从 BST 中删除给定的键 k,并返回更新后的 BST。因此,如果树类似于:
并且键 k = 3,则输出树将为:
为了解决这个问题,我们将遵循以下步骤:
定义一个名为 deleteRoot() 的方法来删除根节点,这将按如下方式工作
如果根节点为空,则返回 null
如果根节点没有右子树,则返回根节点的左子树
x := 根节点的中序后继
将 x 的左子树设置为 left := 根节点的左子树
返回根节点的右子树
delete 方法将如下所示
如果根节点为空或根节点的值为键,则返回 deleteRoot(root)
curr := 根节点
创建一个无限循环,并执行以下操作
x := curr 节点的值
如果 key < x,则
如果 curr 的左子树为空或 curr 的左子树的值为 key,则
curr 的左子树 := deleteRoot(curr 的左子树) 并退出循环。
curr := curr 的左子树
否则
如果 curr 的右子树为空或 curr 的右子树的值为 key,则
curr 的右子树 := deleteRoot(curr 的右子树) 并退出循环。
curr := curr 的右子树
返回根节点
让我们看看以下实现以获得更好的理解:
示例
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else { q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else { q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr == NULL || curr->val == 0){ cout << "null" << ", "; } else { cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if(root == NULL || root->val == key) return deleteRoot(root); TreeNode* curr = root; while(1) { int x = curr->val; if(key < x){ if(curr->left == NULL || curr->left->val == key){ curr->left = deleteRoot(curr->left); break; } curr = curr->left; } else { if(curr->right == NULL || curr->right->val == key){ curr->right = deleteRoot(curr->right); break; } curr = curr->right; } } return root; } TreeNode* deleteRoot(TreeNode* root){ if(!root || root->val == 0)return NULL; if(root->right == NULL) return root->left; TreeNode* x = root->right; while(x->left)x = x->left; x->left = root->left; return root->right; } }; main(){ vector<int> v = {5,3,6,2,4,NULL,7}; TreeNode *root = make_tree(v); Solution ob; tree_level_trav(ob.deleteNode(root, 3)); }
输入
[5,3,6,2,4,null,7] 3
输出
[5, 4, 6, 2, null, 7, ]
广告