知识点
二叉搜索树:设x为二叉搜索树的结点,如果y为x的左子树中的结点,那么y的值小于等于x;同理,若在x的右子树,则y的值大于等于x。
问题链接
ALDS1_8_A:Binary Search Tree I
问题内容
insert是插入操作,print是输出中序和前序遍历结果的操作
思路
按照题目的伪代码提示去构建,前序中序遍历用前面的例子代码即可。
代码
#include<iostream>
#include<cstdio>
using namespace std;
const int MAX = 100005;
struct Node {
int key;
Node *parent, *left, *right;
};
Node *root, *NIL;
//前序排序
void PreorderTreeWalk(Node *u) {
if (u == NIL)
return;
printf(" %d", u->key);
PreorderTreeWalk(u->left);
PreorderTreeWalk(u->right);
}
//中序排序
void InorderTreeWalk(Node *u) {
if (u == NIL)
return;
InorderTreeWalk(u->left);
printf(" %d", u->key);
InorderTreeWalk(u->right);
}
void insert(int value) {
Node *y = NIL, *x = root;
Node *z = new Node();
z->key = value;
z->left = z->right = NIL;
// 从根结点往下遍历
while (x != NIL) {
y = x;
// z 比 x 小, 则从x的左侧遍历
// z 比 x 大, 则从x的右侧遍历
if (z->key < x->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
// 没有父结点的是root
if (y == NIL) {
root = z;
}else {
// z 比 y 小, 则在y的左侧
// z 比 y 大, 则在y的右侧
if (z->key < y->key)
y->left = z;
else
y->right = z;
}
}
int main() {
int n, value;
char s[200];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", s);
if (s[0] == 'i') {
scanf("%d", &value);
insert(value);
}else {
InorderTreeWalk(root);
printf("\n");
PreorderTreeWalk(root);
printf("\n");
}
}
return 0;
}