树(懒得打字直接放图 (
-
以下部分来自百度百科
-
二叉树
类型
相关术语
二叉树性质
辨析
1. 树中结点的最大度数没有限制,而二叉树结点的最大度数为2;
2. 树的结点无左、右之分,而二叉树的结点有左、右之分。
void QWE1 ( tree * a )
{
printf ( "%c" , a -> a );//此时a结点中存的字符可以理解为根
if ( a -> ltree !=NULL )
QWE1 ( a -> ltree );//a的左子树
if ( a -> rtree !=NULL )
QWE1 ( a -> rtree );//a的右子树
}
首先中序遍历左(右)子树,再访问根,最后中序遍历右(左)子树,C语言代码如下
{
if ( a -> ltree != 0 )
QWE2 ( a -> ltree ); //a的左子树
printf ( "%c" , a -> a ); //此时a结点中存的字符可以理解为根
if ( a -> rtree != 0 )
QWE2 ( a -> rtree );//a的右子树
}
首先后序遍历左(右)子树,再后序遍历右(左)子树,最后访问根,C语言代码如下
void QWE3 ( struct qwe * a )
{
if ( a -> ltree != 0 )
QWE3 ( a -> ltree );//a的左子树
if ( a -> rtree != 0 )
QWE3 ( a -> rtree );//a的右子树
printf ( "%c" , a -> a );//此时a结点中存的字符可以理解为根
}
层次遍历
即按照层次访问,通常用队列来做。访问根,访问子女,再访问子女的子女(越往后的层次越低)(两个子女的级别相同)
{
if ( a -> ltree != 0 )
printf ( "%c" , a -> ltree -> a );//a的左子树
if ( a -> rtree != 0 )
printf ( "%c" , a -> rtree -> a );//a的右子树
if ( a -> ltree != 0 )
QWE4 ( a -> ltree );//a的左子树
if ( a -> rtree != 0 )
QWE4 ( a -> rtree ); //a的右子树
}
二叉树的构建
一般的是用递归函数调用 其实如果是满二叉树数组也可以 就是1->2,3;2->4,5;3->6,7,,,,,,i->2*i,2*i+1;
//一般的
tree* QWE()
{
char a;
tree *t;
t=NULL;
t=new tree();//new是自动配适返回类型
scanf("%c",&a);
t->a=a;
if(a=='#')
return 0;
else
{ t->ltree=QWE();
t->rtree=QWE();
return t;
}
};//先序遍历构建的(多组输入int o=0,d;
tree* QWE(char *q)
{
char a;
tree *t;
t=NULL;
t=new tree();//new是自动配适返回类型
t->a=*(q+o);
if(t->a=='#')
{
d--;
return 0;
}
else
{
t->c=d;
o++;
t->ltree=QWE(q);
o++;
t->rtree=QWE(q);
return t;
}
};
//加个题 划一划水 面的看不懂代码 SDIBT 2749
根据给定的字符串生成二叉树并前序、中序、后序此二叉树。
Input
给定一字符串,其中#表示空。
例:上图输入为
HDB#A##C##G#FE###
Output
分别输出此二叉树前序、中序和后序。
Sample Input
HDB#A##C##G#FE###
Sample Output
HDBACGFE BADCHGEF ABCDEFGH
Hint
做完的同学还可以线索化二叉树后再进行先序、中序和后序遍历。
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<deque>
#include<stack>
#include<queue>
#include<algorithm>
#include<math.h>
#include<deque>
using namespace std;
struct qwe{
char a;
struct qwe *ltree;
struct qwe *rtree;
};
struct qwe *A;
struct qwe* QWE()
{
char a;
struct qwe *t;
t=NULL;
t=new struct qwe();
scanf("%c",&a);
t->a=a;
if(a=='#')
return 0;
else
{
t->ltree=QWE();
t->rtree=QWE();
return t;
}
};
void QWE1(struct qwe *a)
{
printf("%c",a->a);
if(a->ltree!=0)
QWE1(a->ltree);
if(a->rtree!=0)
QWE1(a->rtree);
}
void QWE2(struct qwe *a)
{
if(a->ltree!=0)
QWE2(a->ltree);
printf("%c",a->a);
if(a->rtree!=0)
QWE2(a->rtree);
}
void QWE3(struct qwe *a)
{
if(a->ltree!=0)
QWE3(a->ltree);
if(a->rtree!=0)
QWE3(a->rtree);
printf("%c",a->a);
}
int main()
{
int b,c,d,i,j,k;
struct qwe *a;
a=new struct qwe();
a=QWE();
QWE1(a);
printf("\n");
QWE2(a);
printf("\n");
QWE3(a);
printf("\n");
return 0;
}