使用链表实现二叉搜索树的 C++ 程序
这是一个C++程序,使用链表实现二叉搜索树。
函数和伪代码
算法
Begin Take the nodes of the tree as input. Create a structure nod to take the data d, a left pointer l and a right r as input. Create a function create() to insert nodes into the tree: Initialize c = 0 as number of nodes. Perform while loop till c < 6: Enter the root. Enter the value of the node, if it is greater than root then entered as right otherwise left. Create a function inorder() to traverse the node as inorder as: Left – Root – Right. Create a function preorder() to traverse the node as preorder as: Root – Left – Right. Create a function postorder() to traverse the node as preorder as: Left – Right – Root From main(), call the functions and print the result. End
示例代码
#include <iostream>
using namespace std;
struct nod {
nod *l, *r;
int d;
}*r = NULL, *p = NULL, *np = NULL, *q;
void create() {
int v,c = 0;
while (c < 6) {
if (r == NULL) {
r = new nod;
cout<<"enter value of root node\n";
cin>>r->d;
r->r = NULL;
r->l = NULL;
} else {
p = r;
cout<<"enter value of node\n";
cin>>v;
while(true) {
if (v< p->d) {
if (p->l == NULL) {
p->l = new nod;
p = p->l;
p->d = v;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
} else if (p->l != NULL) {
p = p->l;
}
} else if (v >p->d) {
if (p->r == NULL) {
p->r = new nod;
p = p->r;
p->d = v;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
} else if (p->r != NULL) {
p = p->r;
}
}
}
}
c++;
}
}
void inorder(nod *p) {
if (p != NULL) {
inorder(p->l);
cout<<p->d<<endl;
inorder(p->r);
}
}
void preorder(nod *p) {
if (p != NULL) {
cout<<p->d<<endl;
preorder(p->l);
preorder(p->r);
}
}
void postorder(nod *p) {
if (p != NULL) {
postorder(p->l);
postorder(p->r);
cout<<p->d<<endl;
}
}
int main() {
create();
cout<<" traversal in inorder\n";
inorder(r);
cout<<" traversal in preorder\n";
preorder(r);
cout<<" traversal in postorder\n";
postorder(r);
}输出
enter value of root node 7 enter value of node 6 value entered in left enter value of node 4 value entered in left enter value of node 3 value entered in left enter value of node 2 value entered in left enter value of node 1 value entered in left traversal in inorder 1 2 3 4 6 7 traversal in preorder 7 6 4 3 2 1 traversal in postorder 1 2 3 4 6 7
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP