建树的两种方法

数组建树

问题 K: 查找二叉树

时间限制: 1 Sec  内存限制: 128 MB
提交: 72  解决: 37
[提交][状态][讨论版][命题人: 外部导入]

题目描述

已知一棵二叉树用邻接表结构存储,中序查找二叉树中值为x的结点,并指出是

第几个结点。

输入

       第一行n为二叉树的结点个树,n<=100;第二行x表示要查找的结点的值;以下第一列数据是各结点的值,第二列数据是左儿子结点编号,第三列数据是右儿子结点编号。

输出

输出要查找的结点数目。

样例输入

7
15
5 2 3
12 4 5
10 0 0
29 0 0
15 6 7
8 0 0
23 0 0

样例输出

4
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
using namespace std;
struct node{
    int d;
    int left;
    int right;
}q[105];
int n,a;
int ans=0;
void inorder(int k)
{
    if(q[k].left)
        inorder(q[k].left);
    ans++;
    if(q[k].d==a)
    {
        cout<<ans<<endl;
        exit(0);
    }
    if(q[k].right)
        inorder(q[k].right);
}
int main()
{
    cin>>n>>a;
    for(int i=1;i<=n;i++)
        cin>>q[i].d>>q[i].left>>q[i].right;
    inorder(1);
    return 0;
}

题目描述

由于先序、中序和后序序列中的任一个都不能唯一确定一棵二叉树,所以对二叉树做如下处理,将二叉树的空结点用·补齐,如图所示。我们把这样处理后的二叉树称为原二叉树的扩展二叉树,扩展二叉树的先序和后序序列能唯一确定其二叉树。现给出扩展二叉树的先序序列,要求输出其中序和后序序列。

输入

输入扩展二叉树的先序序列

输出

输出其中序和后序序列

样例输入

ABD..EF..G..C..

样例输出

DBFEGAC
DFGEBCA

链表建树和遍历

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
using namespace std;
typedef char datatype;
typedef struct node{
	datatype data;
	struct node *lchild,*rchild;
}node,*bitree;
node *creatbitreep(){
	char ch;
	node *t;
ch=getchar();
	if(ch=='.')t=NULL;
	else{
		t=(node*)malloc(sizeof(node));
		t->data=ch;
		t->lchild=creatbitreep();
		t->rchild=creatbitreep();
	}return t;
}
void postorder(node *t){
	if(t){
		postorder(t->lchild);
		postorder(t->rchild);
		printf("%c",t->data);
		
	}
}
void inorder(node *t){
	if(t){
		inorder(t->lchild);
		printf("%c",t->data);
		inorder(t->rchild);
	}
}
int main(){
	node *tree;
	tree=creatbitreep();
	inorder(tree);
	printf("\n");
	postorder(tree);
}

猜你喜欢

转载自blog.csdn.net/qq_40570748/article/details/81487913