【发布时间】:2019-07-30 10:03:11
【问题描述】:
我正在解决一个问题,它说:
编写一个程序,在二叉搜索树上处理以下查询:
- i x:在 BST 中插入 x
- d x:从 BST 中删除 x
输入格式
第1行包含一个整数Q,查询次数
接下来的 Q 行是 i x 或 d x 的形式
输出格式
对于每个查询,打印 x 在 BST 中的位置
如果一个节点的位置是p,那么它的左右孩子的位置分别是2*p和2*p+1
根节点的位置是1
11 //Queries
i 15 //i=insert; d=delete
i 9
i 25
i 8
i 13
i 18
i 19
i 7
i 11
d 9
i 14
一切正常,直到我删除节点 9。然后节点 14 的位置变为 5。见图:最初,
15
/ \
9 25
/ \ /
8 13 18
/ / \
7 11 19
删除9后;
15
/ \
11 25
/ \ /
8 13 18
/ \
7 19
插入14后
15
/ \
11 25
/ \ /
8 14 18
/ / \
7 13 19
正确的格式应该是
15
/ \
11 25
/ \ /
8 13 18
/ \ \
7 14 19
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll position=1;
struct BSTNode
{
int data;
BSTNode *left,*right;
};
BSTNode *getNewNode(int data)
{
BSTNode *newNode = new BSTNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode; //returns address of new node
}
BSTNode* insert(BSTNode *root,int data)
{
if(root==NULL){
root = getNewNode(data);
}
else if(data<root->data)
{
root->left = insert(root->left,data);
}
else if(data>root->data)
{
root->right = insert(root->right,data);
}
return root;
}
BSTNode *findMin(BSTNode *root)
{
if(root->left ==NULL)
{
return root;
}
else
findMin(root->left);
}
bool search(BSTNode *root,int data)
{
if(root == NULL)
{
return 0;
}
if(data<root->data)
{
position=2*position;
search(root->left,data);
}
else if(data>root->data)
{
position=2*position+1;
search(root->right,data);
}
else
{
cout<<"Found";
return 1;
}
}
BSTNode* delet(BSTNode* root,int data)
{
if(root == NULL)
{
return 0;
}
else if(data<root->data)
{
root->left = delet(root->left,data);
}
else if(data>root->data)
{
root->right = delet(root->right,data);
}
else //Found
{
//CASE 1:No child
if(root->left == root->right ==NULL)
{
delete root;
root = NULL;
}
//CASE2: One child
else if(root->left == NULL)
{
BSTNode *temp= root;
root = root->right;
delete temp;
}
else if(root->right == NULL)
{
BSTNode *temp=root;
root= root->left;
delete temp;
}
//CASE 3: TWO CHILD
else
{
BSTNode *temp = findMin(root->right);
root->data = temp->data;
root->right = delet(root->right,root->data);
}
return root;
}
}
int main()
{
BSTNode* root = NULL; //rootptr- pointer to node
//tree is empty
int n,input,data,del;
char c;
cin>>n;
while(n--)
{
cin>>c;
cin>>input;
if(c=='i')
{
root = insert(root,input);
search(root,input);
}
if(c=='d')
{
search(root,input);
delet(root,input);
}
cout<<position<<endl;
position=1;
}
return 0;
}
这种可能的插入是如何作为叶节点完成的呢?
【问题讨论】:
-
嘿,Harshal,看起来一切都很好。您面临什么问题?
-
@FarukHossain 当我删除 9 时,它在其右侧节点上被 11 替换,但当我插入 14 时,它正在替换 13 并将其添加为叶子,而 14 应该已添加为叶子
-
一些 C++ 建议: 1. 有帮助时不要使用
#define。因此,如果必须,请执行using ll = long long;。 2.stackoverflow.com/questions/1452721/… 3.使用类:代替getNewNode,给BSTNode一个构造函数。 4. 使用nullptr而不是NULL,因为nullptr提供了更多的类型安全性。 5. 尽可能使用std::unique_ptr;原始指针自找麻烦。 -
你永远不应该
#include <bits/stdc++.h>。它不是正确的 C++。它破坏了便携性并养成了糟糕的习惯。见Why should I not#include <bits/stdc++.h>。 -
另外,避免
using namespace std;。这被认为是不好的做法。见Why is “using namespace std;” considered bad practice?
标签: c++ tree insert binary-search-tree