算法学习19-实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式及深搜和宽搜
文章目录
实现二叉树的先序、中序、后序遍历
相关知识
二叉树的遍历主要有三种:
(1)先(根)序遍历(根左右)
(2)中(根)序遍历(左根右)
(3)后(根)序遍历(左右根)
(4)先(根)序遍历(逐层输出)
举个例子:
先(根)序遍历(根左右):A B D H E I C F J K G
中(根)序遍历(左根右) : D H B E I A J F K C G
后(根)序遍历(左右根) : H D I E B J K F G C A
递归行为
#include<iostream>
using namespace std;
struct node {
int Number;
struct node* Left;
struct node* Right;
};
//输出信息
void PrintList(int Number)
{
printf("%d ", Number);
}
//前遍历
void PreOrder(struct node* root)
{
if (root == NULL)
return;
PrintList(root->Number);
PreOrder(root->Left);
PreOrder(root->Right);
}
//中遍历
void InOrder(struct node* root)
{
if (root == NULL)
return;
InOrder(root->Left);
PrintList(root->Number);
InOrder(root->Right);
}
//后遍历
void PostOrder(struct node* root)
{
if (root == NULL)
return;
PostOrder(root->Left);
PostOrder(root->Right);
PrintList(root->Number);
}
//
int GetMaxWidth(struct node*pointer){
int width[10];//加入这棵树的最大高度不超过10
int maxWidth=0;
int floor=1;
if(pointer){
width[floor]++;
floor++;
if (pointer->Left)
width[floor]++;
if (pointer->Right)
width[floor]++;
if(maxWidth<width[floor])
maxWidth=width[floor];
GetMaxWidth(pointer->Left);
floor--;//记得退回一层,否则会出错。因为已经Get过了,所以要及时的返回。
GetMaxWidth(pointer->Right);
}
return maxWidth;
}
非递归行为
#include <malloc.h>
#include <stack>
#include <iostream>
using namespace std;
typedef struct BiTNode{
char data;
BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T)//建树,按先序顺序输入节点
{
char ch;
scanf("%c",&ch);
if(ch==' ')
{
T=NULL;
return;
}
else
{
T=(BiTree)malloc(sizeof(BiTNode));
if(!T)
exit(1);
T-