當前位置:首頁 » 操作系統 » 按層次遍歷二叉樹演算法

按層次遍歷二叉樹演算法

發布時間: 2023-05-02 08:47:14

❶ 以二叉連表做存儲結構,試編寫按層次順序遍歷二叉樹的演算法

//二叉樹,按層次訪問
//引用如下地址的思想,設計一個演算法層序遍歷二叉樹(同一層從左到右訪問)。思想:用一個隊列保存被訪問的當前節點的左右孩子以實現層序遍歷。
//http://..com/link?url=a9ltidaf-SQzCIsa
typedef struct tagMyBTree
{
int data;
struct tagMyBTree *left,*right;
}MyBTree;

void visitNode(MyBTree *node)
{
if (node)
{
printf("%d ", node->data);
}

}
void visitBTree(queue<MyBTree*> q);
void createBTree(MyBTree **tree)
{
int data = 0;
static int initdata[15] = {1,2,4,0,0,5,0,0,3,6,0,0,7,0,0};//構造成滿二叉樹,利於查看結果
static int i = 0;
//scanf("%d", &data);
data = initdata[i++];
if (data == 0)
{
*tree = NULL;
}
else
{
*tree = (MyBTree*)malloc(sizeof(MyBTree));
if (*tree == NULL)
{
return;
}
(*tree)->data = data;

createBTree(&(*tree)->left);

createBTree(&(*tree)->right);

}
}

void visitBTreeTest()
{
queue<MyBTree*> q;
MyBTree *tree;
createBTree(&tree);
q.push(tree);
visitBTree(q);
}

void visitBTree(queue<MyBTree*> q)
{
if (!q.empty())
{
MyBTree *t = q.front();
q.pop();
visitNode(t);
if (t->left)
{
q.push(t->left);
}
if (t->right)
{
q.push(t->right);
}

visitBTree(q);
}
}

❷ 編寫按層次順序(同一層從左至右)遍歷二叉樹的演算法

#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) 開始的 用隊列方法遍歷的

❸ 在按層次遍歷二叉樹的演算法中,需要藉助的輔助數據結構是

輔助的就是隊列了,如果是堆棧就成了深度優先演算法了;其實這里輔助結構決定了演算法的性質,你可以換成最大堆,最小堆等,就可以達到很多不同的效果

❹ 數據結構二叉樹的基本操作~~~~

用遞歸的方法實現以下演算法:
1.以二叉鏈表表示二叉樹,建立一棵二叉樹;
2.輸出二叉樹的前序遍歷結果;
3.輸出二叉樹的猛猛備中序遍歷結果;
4.輸出二叉樹的後序遍歷結果;
5.統計二叉樹的葉結點個數;
6.統計二叉樹的結點個數;
7.計算二叉樹的深度。
8.交換二叉樹每個結點的左孩子和右孩子;
#include <malloc.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

#define OK 1
#define NULL 0
#define FALSE 0

typedef struct BiTNode{ //定義鏈式二叉樹結構體
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree T;
char ch;
int flag=0;

int createBiTree(BiTree &T){
//按先序輸入二叉樹中知裂結點的值(一個字元),空格表示空樹
ch=getchar();
if(ch==' ')T=NULL; //表示空樹
else if(ch==10)flag=1; //結點信息輸入錯誤則返回0
else {
T=(BiTNode*)malloc(sizeof(BiTree));
if(!T)exit(1);//空間分配不成功則退出
T->data=ch; //生成根結點
createBiTree(T->lchild); //生成左子樹
createBiTree(T->rchild); //生成右子樹
}//else
return OK;
}//createBiTree

int PreOrderTraverse(BiTree T){ //先序遍歷二叉樹的遞歸演算法
if(T){
printf("%c",T->data); //訪問根結點
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}//if
return OK;
}

int InOrderTraverse(BiTree T){ //中序
if(T){
InOrderTraverse(T->lchild);
printf("%c",T->data); //訪問根結點
InOrderTraverse(T->rchild);
}//if
return OK;
}

int PostOrderTraverse(BiTree T){ // 後序
if(T){
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%c",T->data); //訪問根結點
}
return OK;
}

int NodeCount(BiTree T){ //
if(T==NULL) return 0;// 如果是空樹,則結點個數為0
else return 1+NodeCount(T->lchild)+NodeCount(T->rchild);
//否則結點個數為1+左子樹的結點個數+右子樹的結點個數
}

int LeafNodeCount(BiTree T ){
if(!T)return 0; //如果是空樹,則葉子個數為枝毀0;
else if(LeafNodeCount(T->lchild)+LeafNodeCount(T->rchild)==0)return 1;//如果是葉子結點,則葉子結點個數為1
else return LeafNodeCount(T->lchild)+LeafNodeCount(T->rchild);
//否則葉結點個數為左子樹的葉結點個數+右子樹的葉結點個數
}

int Depth(BiTree T){//計算二叉樹的深度
int m,n;
if(T==NULL )return 0;//如果是空樹,則深度為0
else {
m=Depth(T->lchild);//計算左子樹的深度記為m
n=Depth(T->rchild);//計算右左子樹的深度記為n
if(m>n) return(m+1);//二叉樹的深度為m 與n的較大者加1
else return (n+1);
}
}
void Exchange1(BiTree T)
{
BiTree temp;
if(T)
{
Exchange1(T->lchild);
Exchange1(T->rchild);
temp=T->lchild;
T->lchild=T->rchild;
T->rchild=temp;
}
}

void main(){
int no,out=1;
char choose;
//*****************************主界面**********************************
while(out){
system("cls");
printf("\n這是實驗2的程序,請按照說明使用:\n");
printf("1.以二叉鏈表表示二叉樹,建立一棵二叉樹,請輸入1");
printf("\n2.輸出二叉樹的前序遍歷結果,請輸入2");
printf("\n3.輸出二叉樹的中序遍歷結果,請輸入3");
printf("\n4.輸出二叉樹的後序遍歷結果請輸入4");
printf("\n5.統計二叉樹的結點個數,請輸入5");
printf("\n6.統計二叉樹的葉結點個數,請輸入6");
printf("\n7.計算二叉樹的深度,請輸入7");
printf("\n8. 交換二叉樹的左右孩子,請輸入8");
printf("\n9.退出,請輸入其他\n");
//********************處理輸入的選項************************************
choose=getch();
switch(choose){
case '1':
system("cls");
printf("\n請輸入二叉鏈表各結點信息建立二叉樹,空樹用空格表示:\n");
if(createBiTree(T)==0||flag==1){ //結點輸入錯誤!
printf("輸入錯誤,請重新輸入結點信息!\n");
getch();break;}
else
printf("輸入完畢!");//成功建立二叉鏈表
getch();break;
case '2':
printf("\n先序遍歷的結果是:");
PreOrderTraverse(T);
getch();break;
case '3':
printf("\n中序遍歷的結果是:");
InOrderTraverse(T);
getch();break;
case '4':
printf("\n後序遍歷的結果是:");
PostOrderTraverse(T);
getch();break;
case '5':
no=NodeCount(T);
printf("\n總結點個數為:%d\n",no);
getch();break;
case '6':
printf("\n葉子結點的個數為:%d\n",LeafNodeCount(T));
getch();break;
case '7':
printf("\n二叉樹深度為:%d\n",Depth(T));
getch();break;
case '8':
printf("\n交換後的結果為:");
Exchange1(T);
PostOrderTraverse(T);
getch();break;
default :
printf("\n你輸入的是:其他\n");
getch();
out=0;
} //end switch
}//end of while
system("cls");
printf("\n\n\t\t歡迎使用,再見!");
}

碉堡了!

java實現二叉樹層次遍歷

import java.util.ArrayList;

public class TreeNode {
private TreeNode leftNode;
private TreeNode rightNode;
private String nodeName;
public TreeNode getLeftNode() {
return leftNode;
}

public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}

public TreeNode getRightNode() {
return rightNode;
}

public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}

public String getNodeName() {
return nodeName;
}

public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public static int level=0;

public static void findNodeByLevel(ArrayList<TreeNode> nodes){
if(nodes==null||nodes.size()==0){
return ;
}
level++;
ArrayList<TreeNode> temp = new ArrayList();
for(TreeNode node:nodes){
System.out.println("第"+level+"層:"+node.getNodeName());
if(node.getLeftNode()!=null){
temp.add(node.getLeftNode());
}
if(node.getRightNode()!=null){
temp.add(node.getRightNode());
}
}
nodes.removeAll(nodes);
findNodeByLevel(temp);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode();
root.setNodeName("root");
TreeNode node1 = new TreeNode();
node1.setNodeName("node1");

TreeNode node3 = new TreeNode();
node3.setNodeName("node3");

TreeNode node7 = new TreeNode();
node7.setNodeName("node7");
TreeNode node8 = new TreeNode();
node8.setNodeName("node8");

TreeNode node4 = new TreeNode();
node4.setNodeName("node4");

TreeNode node2 = new TreeNode();
node2.setNodeName("node2");

TreeNode node5 = new TreeNode();
node5.setNodeName("node5");
TreeNode node6 = new TreeNode();
node6.setNodeName("node6");

root.setLeftNode(node1);

node1.setLeftNode(node3);

node3.setLeftNode(node7);
node3.setRightNode(node8);

node1.setRightNode(node4);

root.setRightNode(node2);

node2.setLeftNode(node5);
node2.setRightNode(node6);

ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
nodes.add(root);
findNodeByLevel(nodes);

}

}

❻ 設二叉樹以二叉鏈表存儲,試設計演算法,實現二叉樹的層序遍歷。

按層次遍歷演算法如下:
#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);
}
}

❼ 試完成二叉樹按層次(同一層自左至右)遍歷的演算法。

#include "iostream.h"
#include "stdlib.h"
#include "stdio.h"

typedef char ElemType;//定義二叉樹結點值的類型為字元型
const int MaxLength=10;//結點個數不超過10個

typedef struct BTNode{
ElemType data;
struct BTNode *lchild,*rchild;
}BTNode,* BiTree;

void CreateBiTree(BiTree &T){//按先序次序輸入,構造二叉鏈表表示的二叉樹T,空格表示空樹
// if(T) return;
char ch;
ch=getchar(); //不能用cin來輸入,在cin中不能識別空格。
if(ch==' ') T=NULL;
else{
if(!(T=(BTNode *)malloc(sizeof(BTNode)))) cout<<"malloc fail!";
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}

void PreOrderTraverse(BiTree T){//先序遍歷
if(T){
cout<<T->data<<' ';
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void InOrderTraverse(BiTree T){//中序遍歷
if(T){
InOrderTraverse(T->lchild);
cout<<T->data<<' ';
InOrderTraverse(T->rchild);
}
}
void PostOrderTraverse(BiTree T){//後序遍歷
if(T){
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
cout<<T->data<<' ';
}
}
void LevelOrderTraverse(BiTree T){//層序遍歷

BiTree Q[MaxLength];
int front=0,rear=0;
BiTree p;
if(T){ //根結點入隊
Q[rear]=T;
rear=(rear+1)%MaxLength;
}
while(front!=rear){
p=Q[front]; //隊頭元素出隊
front=(front+1)%MaxLength;
cout<<p->data<<' ';
if(p->lchild){ //左孩子不為空,入隊
Q[rear]=p->lchild;
rear=(rear+1)%MaxLength;
}
if(p->rchild){ //右孩子不為空,入隊
Q[rear]=p->rchild;
rear=(rear+1)%MaxLength;
}
}

}
//非遞歸的先序遍歷演算法
void NRPreOrder(BiTree bt)
{ BiTree stack[MaxLength],p;
int top;
if (bt!=NULL){
top=0;p=bt;
while(p!=NULL||top>0)
{ while(p!=NULL)
{
cout<<p->data;
stack[top]=p;
top++;
p=p->lchild;
}
if (top>0)
{ top--; p=stack[top]; p=p->rchild; }
}
}
}
//非遞歸的中序遍歷演算法
void NRInOrder(BiTree bt)
{ BiTree stack[MaxLength],p;
int top;
if (bt!=NULL){
top=0;p=bt;
while(p!=NULL||top>0)
{ while(p!=NULL)
{

stack[top]=p;
top++;
p=p->lchild;
}
if (top>0)
{ top--; p=stack[top];cout<<p->data; p=p->rchild; }
}
}
}
//非遞歸的後序遍歷演算法
/*bt是要遍歷樹的根指針,後序遍歷要求在遍歷完左右子樹後,再訪問根。
需要判斷根結點的左右子樹是否均遍歷過。
可採用標記法,結點入棧時,配一個標志tag一同入棧
(1:遍歷左子樹前的現場保護,2:遍歷右子樹前的現場保護)。
首先將bt和tag(為1)入棧,遍歷左子樹;
返回後,修改棧頂tag為2,遍歷右子樹;最後訪問根結點。*/

typedef struct
{
BiTree ptr;
int tag;
}stacknode;

void NRPostOrder(BiTree bt)
{
stacknode s[MaxLength],x;
BiTree p=bt;
int top;
if(bt!=NULL){
top=0;p=bt;
do
{
while (p!=NULL) //遍歷左子樹
{
s[top].ptr = p;
s[top].tag = 1; //標記為左子樹
top++;
p=p->lchild;
}

while (top>0 && s[top-1].tag==2)
{
x = s[--top];
p = x.ptr;
cout<<p->data; //tag為R,表示右子樹訪問完畢,故訪問根結點
}

if (top>0)
{
s[top-1].tag =2; //遍歷右子樹
p=s[top-1].ptr->rchild;
}
}while (top>0);}
}//PostOrderUnrec

int BTDepth(BiTree T){//求二叉樹的深度
if(!T) return 0;
else{
int h1=BTDepth(T->lchild);
int h2=BTDepth(T->rchild);
if(h1>h2) return h1+1;
else return h2+1;
}
}

int Leaf(BiTree T){//求二叉樹的葉子數
if(!T) return 0;
else if(!T->lchild&&!T->rchild) return 1;
else return(Leaf(T->lchild)+Leaf(T->rchild));
}

int NodeCount(BiTree T){//求二叉樹的結點總數
if(!T) return 0;
else return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}

void main(){
BiTree T;
T=NULL;
int select;
//cout<<"請按先序次序輸入各結點的值,以空格表示空樹(輸入時可連續輸入):"<<endl;
// CreateBiTree(T);
while(1){
cout<<"\n\n請選擇要執行的操作:\n";
cout<<"1.創建二叉樹\n";
cout<<"2.二叉樹的遞歸遍歷演算法(前、中、後)\n";
cout<<"3.二叉樹的層次遍歷演算法\n";
cout<<"4.求二叉樹的深度\n";
cout<<"5.求二叉樹的葉子結點\n";
cout<<"6.求二叉樹的結點總數\n";
cout<<"7.二叉樹的非遞歸遍歷演算法(前、中、後)\n"; //此項可選做
cout<<"0.退出\n";
cin>>select;
switch(select){
case 0:return;
case 1:
cout<<"請按先序次序輸入各結點的值,以空格表示空樹(輸入時可連續輸入):"<<endl;
CreateBiTree(T);
break;
case 2:
if(!T) cout<<"未建立樹,請先建樹!";
else{
cout<<"\n先序遍歷:\n";
PreOrderTraverse(T);
cout<<"\n中序遍歷:\n";
InOrderTraverse(T);
cout<<"\n後序遍歷:\n";
PostOrderTraverse(T);
}
break;
case 3:
cout<<"\n層序遍歷:\n";
LevelOrderTraverse(T);
break;
case 4:
cout<<"二叉樹的深度為:\n";
cout<<BTDepth(T);
break;
case 5:
cout<<"\n葉子節點數:\n";
cout<<Leaf(T);
break;
case 6:
cout<<"總節點數:\n";
cout<<NodeCount(T);
break;
case 7:
if(!T) cout<<"未建立樹,請先建樹!";
else{
cout<<"\n先序遍歷:\n";
NRPreOrder(T);
cout<<"\n中序遍歷:\n";
NRInOrder(T);
cout<<"\n後序遍歷:\n";
NRPostOrder(T);
}
break;
default:
cout<<"請確認選擇項:\n";
}//end switch
}//end while

}
參考資料:找來的,你看看吧!

❽ 二叉樹的層次遍歷

設計一個演算法層序遍歷二叉樹(同一層從左到右訪問)。思想:用一個隊列保存被訪問的當前節點的左右孩子以實現層序遍歷。
void HierarchyBiTree(BiTree Root){
LinkQueue *Q; // 保存當前節點的左右孩子的隊列

InitQueue(Q); // 初始化隊列

if (Root == NULL) return ; //樹為空則返回
BiNode *p = Root; // 臨時保存樹根Root到指針p中
Visit(p->data); // 訪問根節點
if (p->lchild) EnQueue(Q, p->lchild); // 若存在左孩子,左孩子進隊列
if (p->rchild) EnQueue(Q, p->rchild); // 若存在右孩子,右孩子進隊列

while (!QueueEmpty(Q)) // 若隊列不空,則層序遍歷 { DeQueue(Q, p); // 出隊列
Visit(p->data);// 訪問當前節點

if (p->lchild) EnQueue(Q, p->lchild); // 若存在左孩子,左孩子進隊列
if (p->rchild) EnQueue(Q, p->rchild); // 若存在右孩子,右孩子進隊列
}

DestroyQueue(Q); // 釋放隊列空間
return ;
這個已經很詳細了!你一定可以看懂的!加油啊!

❾ 二叉樹遍歷方法有幾種

二叉樹遍歷方法最常用的大致有四種:
先序遍歷,也叫先根遍歷。就是先訪問根結點,再訪問左子樹,最後訪問右子樹。
中序遍歷,也叫中根遍歷。就是先訪問左子樹,再訪問根節點,最後訪問右子樹。
後序遍歷,也叫後根遍歷。就是先訪問左子樹,再訪問右子樹,最後訪問根結點。
按層次遍歷,就是對二叉樹從上到下訪問每一層,在每一層中都是按從左到右進行訪問該層中的每一個節點。

❿ 二叉樹的層次遍歷以及用層次遍歷演算法顯示所有葉子節點

#include <iostream>
using namespace std;
struct segtree{int a,b;} tree[10001];
void buildtree(int l,int r,int root = 0) //建樹 { tree[root].a=l; tree[root].b=r; if (l==r) return; int mid=(l+r)>>1; root<<=1; buildtree(l,mid,root+1); buildtree(l,mid,root+2);}
void dfs(int level,int root = 0){ for (int i=1;i<level;i++) cout<<' '; cout<<"Lv"<<level<<" : ["<<tree[root].a<<","<<tree[root].b<<"]\n"; if (tree[root].a!=tree[root].b) { root<<=1; dfs(level+1,root+1); dfs(level+1,root+2); }}
struct {int root,level;} st[100001];
void bfs(){ int top=1,first=0; st[first].root=0; st[first].level=1; while (first<top) { for (int i=st[first].level;i>1;i--) cout<<' '; cout<<"Lv"<<st[first].level<<" : ["<<tree[st[first].root].a<<","<<tree[st[first].root].b<<"]\n"; if (tree[st[first].root].a!=tree[st[first].root].b) { st[top].root=st[first].root*2+1; st[top++].level=st[first].level+1; st[top].root=st[first].root*2+2; st[top++].level=st[first].level+1; } first++; }}
int main(){ int t,i; cout<<"以[1,9]線段樹為例,生成一個二叉樹。\n\n"; buildtree(1,9); cout<<"以深度遍歷該樹(深搜):\n"; dfs(1); cout<<"以深度遍歷該樹(寬搜):\n"; bfs(); system("pause"); return 0;}

熱點內容
javash腳本文件 發布:2024-05-20 01:43:11 瀏覽:829
安卓手機如何登陸刺激戰場國際服 發布:2024-05-20 01:29:02 瀏覽:861
伺服器核庫怎麼找 發布:2024-05-20 01:28:14 瀏覽:375
鹽存儲水分 發布:2024-05-20 01:09:03 瀏覽:810
中國移動用什麼服務密碼 發布:2024-05-20 00:52:10 瀏覽:696
make編譯輸出 發布:2024-05-20 00:37:01 瀏覽:68
4200存儲伺服器 發布:2024-05-20 00:20:35 瀏覽:161
解壓小生活 發布:2024-05-20 00:15:03 瀏覽:143
粘土小游戲伺服器ip 發布:2024-05-20 00:14:00 瀏覽:196
魔獸世界如何快速增加伺服器 發布:2024-05-19 23:53:37 瀏覽:694