二叉樹的建立,先序 中序 後續遞迴和非遞迴遍歷

2021-08-27 16:20:49 字數 3334 閱讀 1489

----------

shengming.h

----------

#pragma once

#include "stdafx.h"

#define n 20

typedef

char elemtype;

typedef

int status;

extern

int coun;

typedef

struct bnode

bnode,*btree;

typedef

struct bnode

bnode;

btree btree_create();

void preorder(btree bt);

void preorder1(btree bt);

void midorder(btree bt);

void midorder1(btree bt);

void postorder(btree bt);

void postorder1(btree bt);

void postorder2(btree bt);

btree build_tree(elemtype* prestart,elemtype* preend,elemtype* midstart,elemtype* midend); //前序 中序推後序

btree build_code(elemtype* poststart,elemtype* postend, elemtype* midstart, elemtype* midend); //後序 中序推前序

dingyi.cpp

#include

"stdafx.h"

#include

"shengming.h"

#include

#include

<

stack

>

using namespace std;

int coun;

btree btree_create()

if (coun ==

0)

coun++;

char ch;

cin >> ch;

bt->

data

= ch;

if (ch ==

'#')

else

return bt;

}void preorder(btree bt)

void preorder1(btree bt) //非遞迴實現

if (!s.empty())

}}void midorder1(btree bt)

if (!s.empty())

}}void midorder(btree bt)

void postorder(btree bt)

void postorder1(btree bt) //非遞迴後續遍歷1

if (!s.empty())

else}}

}void postorder2(btree bt) //非遞迴後續遍歷2

else

}}btree build_tree(elemtype* prestart, elemtype* preend, elemtype* midstart, elemtype* midend) //前序 中序推後序

root->

data

=*prestart; //把前序的第乙個節點儲存為根節點

root->lchild =

null;

root->rchild =

null;

if (midstart == midend) //沒有if語句也可以得出結果

elemtype* mid;

mid = midstart;

while (*prestart !=

*mid)

//左子樹長度

int length;

length = mid - midstart;

//重建左子樹

if (length >

0) root->lchild = build_tree(prestart+

1,prestart+length-

1,midstart,midstart+length-

1); //重建右子樹

if (midstart + length < midend)

root->rchild = build_tree(prestart+length+

1,preend,midstart+length+

1,midend);

return root;

}btree build_code( elemtype* poststart,elemtype* postend, elemtype* midstart, elemtype* midend)

cout <<

"*postend="

<<

*postend << endl;

root->

data

=*postend; //把後序的最後乙個節點儲存為根節點

root->lchild =

null;

root->rchild =

null;

if (midstart == midend &&

*midstart ==

*midend) //沒有if語句也可以得出結果

elemtype* mid;

mid = midstart;

while (*postend !=

*mid)

//左子樹長度

int length;

length = mid - midstart;

//重建左子樹

if (length >

0)

//重建右子樹

if (midstart + length < midend)

return root;

}

binarytree.cpp

// binarytree.cpp: 定義控制台應用程式的入口點。

//#include "stdafx.h"

#include "shengming.h"

#include

using

namespace

std;

int main()

二叉樹的先序,中序,後續的遞迴和非遞迴方式

先序遞迴 public static void preorderrecur node head system.out.println head.value preorderrecur head.left preorderrecur head.right 中序遞迴 public static void...

通過先序和中序建立二叉樹

include iostream include queue using namespace std int x 1000 z 1000 struct tree void xzcreate tree t,int xl,int zl,int len for int i 0 z i zl x xl i ...

先序遞迴構造二叉樹 中序遞迴遍歷二叉樹

include stdio.h include malloc.h typedef struct bitnodebitnode,bitree char ch abc de g f int i 0 int createbitree bitree t else return 1 void preorder...