二叉樹 非遞迴先中後序 遞迴非遞迴求深度

2022-09-23 00:13:06 字數 1756 閱讀 3819

#include#include

#include

#define n 50

using

namespace

std;

typedef

struct

treebittree;

//鍵盤輸入

bittree *createtree()}//

陣列輸入

bittree *createtree(int a, int i, int

n)}

//非遞迴先序

void preorder(bittree *bt)

p = stack[top--];

p = p->rchild;

}}//

非遞迴中序

void inorder(bittree *bt)

p = stack[top--];

printf(

"%c

",p->ch);//

和前序的不同之處

p = p->rchild;

}}//

非遞迴後序

void postorder(bittree *bt)

p =stack1[top];

flag = stack2[top--];

if(flag == 1

)

else

}} //

遞迴求二叉樹深度

int depth_1(bittree *bt)

} //

非遞迴求二叉樹深度

int depth_2(bittree *bt)

p =stack1[top];

cur = stack2[top--];

if(p->lchild==null && p->rchild==null)

if(cur >max)

max =cur;

p = p->rchild;

cur++;}}

return

max;

} int

main();

bittree *bt=createtree(a,1,9

); printf(

"前序遍歷非遞迴實現:\n");

preorder(bt);

printf("\n

");printf(

"中序遍歷非遞迴實現:\n");

inorder(bt);

printf("\n

");printf(

"後序遍歷非遞迴實現:\n");

postorder(bt);

printf("\n

");printf(

"depth_recursive:%d

",depth_1(bt));

printf("\n

");printf(

"depth_nonrecursive:%d

",depth_2(bt));

return0;

}

輸入樣例:a/\

b c

/\ \

d e f

/\g h