7-1 建立二叉搜索树并查找父结点
按输入顺序建立二叉搜索树,并搜索某一结点,输出其父结点。
输入格式:
输入有三行: 第一行是n值,表示有n个结点; 第二行有n个整数,分别代表n个结点的数据值; 第三行是x,表示要搜索值为x的结点的父结点。
输出格式:
输出值为x的结点的父结点的值。 若值为x的结点不存在,则输出:It does not exist. 若值为x的结点是根结点,则输出:It doesn’t have parent.
输入样例:
2
20
30
20
输出样例:
It doesn’t have parent.
输入样例:
2
20
30
30
输出样例:
20
#include <iostream>
using namespace std;
struct BinaryTree_Node
{
int key;
BinaryTree_Node* lChild;
BinaryTree_Node* rChild;
BinaryTree_Node(int v) : key(v), lChild(NULL), rChild(NULL) {}
};
typedef BinaryTree_Node* BT_Node;
void search_Root(BT_Node parent, BT_Node node, int key)
{
if (node == NULL)
{
cout << "It does not exist." << endl;
return;
}
if (key == node->key)
{
cout << parent->key << endl;
return;
}
if (key < node->key)
return search_Root(node, node->lChild, key);
else
return search_Root(node, node->rChild, key);
}
void Create_BinaryTree(BT_Node &node, int key)
{
if (node == NULL)
{
node = new BinaryTree_Node(key);
return;
}
if (key < node->key)
Create_BinaryTree(node->lChild, key);
else
Create_BinaryTree(node->rChild, key);
return;
}
int main()
{
BT_Node root = NULL;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int key;
cin >> key;
Create_BinaryTree(root, key);
}
int x;
cin >> x;
if (root == NULL)
{
cout << "It does not exist." << endl;
return 0;
}
if (root->key == x)
{
cout << "It doesn't have parent." << endl;
return 0;
}
search_Root(NULL,root, x);
return 0;
}
7-2 二叉搜索树的删除操作
给出一棵二叉搜索树(没有相同元素), 请输出其删除部分元素之后的层序遍历序列。
删除结点的策略如下:
如果一个结点是叶子结点,则直接删除;
如果一个结点的左子树不为空, 则将该结点的值设置为其左子树上各结点中的最大值,并继续删除其左子树上拥有最大值的结点;
如果一个结点的左子树为空但右子树不为空,则将该结点的值设置为其右子树上各结点中的最小值,并继续删除其右子树上拥有最小值的结点。
输入格式:
每个输入文件包含一个测试用例。每个测试用例的第一行包含一个整数 N (0<N<=100),表示二叉搜索树中结点的个数。 第二行给出该二叉搜索树的先序遍历序列,由 N 个整数构成,以一个空格分隔。第三行给出一个整数K (0<K<N),表示待删除的结点个数。最后一行给出 K 个整数,表示待删除的各个结点上的值。必须按输入次序删除结点。题目保证结点一定能被删除。
输出格式:
在一行中输出删除结点后的层序遍历序列。序列中的数字以一个空格分隔,行末不得有多余空格。
输入样例:
7
4 2 1 3 6 5 7
2
3 6
输出样例:
4 2 5 1 7
if (root == NULL)
return;
queue<pNode> qu;
qu.push(root);
queue<pNode> print;
while (qu.size() != 0)
{
pNode t;
t = qu.front();
qu.pop();
print.push(t);
if (t->lchild != NULL)
qu.push(t->lchild);
if (t->rchild != NULL)
qu.push(t->rchild);
}
while (print.size() > 1)
{
cout << print.front()->data << " ";
print.pop();
}
cout << print.front()->data << endl;
print.pop();
return;
}
int main()
{
int n1, n2;
vector<int> preorder;
cin >> n1;
for (int i = 0; i < n1; i++)
{
int d;
cin >> d;
preorder.push_back(d);
}
pNode root = CreateTree(preorder);
cin >> n2;
if (n1 == 0 && n2 == 0)
return 0;
if (n1 == n2)
return 0;
for (int i = 0; i < n2; i++)
{
int d;
cin >> d;
DeleteNode(root, d,0);
}
Level_Tanverse(root);
return 0;
}