Ⅰ 如何用C語言實現層次遍歷二叉樹
下面是c語言的前序遍歷二叉樹的演算法,在這里假設的節點元素值假設的為字元型,
說明:演算法中用到了結構體,也用到了遞歸的方法,你看看怎麼樣,祝你好運!
#include"stdio.h"
typedef
char
elemtype;
typedef
struct
node
//定義鏈表結構
{
elemtype
data;
//定義節點值
struct
note
*lchild;
//定義左子節點值
struct
note
*rchild;
//定義右節點值
}btree;
preorder(btree
*root)
//前序遍歷
{
if(roof!=null)
//如果不是空節點
{
printf("%c\n",root->data);
//輸出當前節點
preorder(root->lchild);
//遞歸前序遍歷左子節點
preorder(root->rchild);
//遞歸前序遍歷右子節點
}
return;
//結束
}
Ⅱ 設二叉樹以二叉鏈表存儲,試設計演算法,實現二叉樹的層序遍歷。
按層次遍歷演算法如下:
#include <iostream>
using namespace std;
typedef struct treenode { //樹結點結構
int data;
struct treenode *left;
struct treenode *right;
}TreeNode;
typedef struct stack{ //棧結點結構
TreeNode *node;
struct stack *next;
}STACK;
void Traversal(TreeNode *root)
{
STACK *head = NULL;
STACK *tail = NULL;
if (root != NULL) //根結點入棧
{
head = new STACK();
head->next = NULL;
head->node = root;
tail = head;
}
while(head != NULL)
{
STACK *temp;
if (head->node->left != NULL) //棧頂結點的左結點入棧
{
temp = new STACK();
temp->next = NULL;
temp->node = head->node->left;
tail->next = temp;
tail = temp;
}
if (head->node->right != NULL) //棧頂結點的右結點入棧
{
temp = new STACK();
temp->next = NULL;
temp->node = head->node->right;
tail->next = temp;
tail = temp;
}
cout<<head->node->data<<endl; //結點出棧
temp = head;
head = head->next;
delete(head);
}
}
Ⅲ c++二叉樹的幾種遍歷演算法
遍歷二叉樹的所有結點且僅訪問一次。按照根節點位置的不同分為前序遍歷,中序遍歷,後序遍歷(除此之外還有層次遍歷,但不常用,此處不做解釋)。
1.前序遍歷:根節點->左子樹->右子樹(根節點在前面)。
2.中序遍歷:左子樹->根節點->右子樹(根節點在中間)。
3.後序遍歷:左子樹->右子樹->根節點(根節點在後邊)。
例如:求下面樹的三種遍歷:
前序遍歷:abdefgc;
中序遍歷:debgfac;
後序遍歷:edgfbca。
Ⅳ 編寫按層次順序(同一層從左至右)遍歷二叉樹的演算法
#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
typedef struct node
{datatype data;
struct node *lchild,*rchild;
}bitree;
bitree *Q[100];
bitree *creat()
{
bitree *root,*s;
int front,rear;
root=NULL;
char ch;
front=1;rear=0;
ch=getchar();
while(ch!='0'枝伏喊)
{
s=NULL;
if(ch!='@'廳裂)
{s=(bitree *)malloc(sizeof(bitree));
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)
root=s;
else
{
if(s&&Q[front])
if(rear%2==0)
Q[front]->lchild=s;
else
Q[front]->rchild=s;
if(rear%2==1)
front++;
}
ch=getchar();
}
return root;
}
void cengci(bitree *t)
{
bitree *Queue[100],*p;
int front=0,rear=0;
if(t)
{
p=t;
Queue[rear]=p;
rear=(rear+1)%20;
while(front!=rear)
{
p=Queue[front];
printf("%c",p->data);
front=(front+1)%100;
if(p->lchild)
{
Queue[rear]=p->lchild;
rear=(rear+1)%100;
}
if(p->rchild)
{
Queue[rear]=p->rchild;
rear=(rear+1)%20;
}
}
}
}
void main()
{struct node *tree;
tree=(bitree *)malloc(sizeof(bitree));
tree=creat();
cengci(tree);
}
遍歷方法從void cengci(bitree *t) 開始的 用隊列方法遍猛野歷的