樹型結構的建立與遍歷

2022-05-04 20:54:09 字數 3151 閱讀 4771

樹型結構的遍歷是樹型結構演算法的基礎,本程式演示二叉樹的儲存結構的建立和遍歷過程。

(1) 編寫建立二叉樹的二叉鍊錶儲存結構的程式,並(用廣義表的形式)顯示並儲存二叉樹;

(2) 採用二叉樹的二叉鍊錶儲存結構,編寫程式實現二叉樹的先序、中序和後序遍歷的遞迴和非遞迴演算法以及層序遍歷演算法,並顯示二叉樹和相應的遍歷序列;

(3) 在二叉樹的二叉鍊錶儲存結構基礎上,編寫程式實現二叉樹的先序或中序或後序線索鍊錶儲存結構建立的演算法,並(用廣義表的形式)顯示和儲存二叉樹的相應的線索鍊錶;

#include #include 

#include

char s[105

];int tag = 0

;int

top;

typedef

struct

node

node;

typedef

struct

nodeth

nodeth;

nodeth *pre =null;

typedef

struct

ststack;

void printbtree(node *t);

void printbtreeth(nodeth *t);

node *contree1();

void preorder(node *t);

void inorder(node *t);

void postorder(node *t);

void npreorder(node *t);

void ninorder(node *t);

void npostorder(node *t);

void leverorder(node *t);

void inorderth(nodeth *root);

nodeth *prenext(nodeth *p);

nodeth *innext(nodeth *p);

nodeth *postnext(nodeth *p);

nodeth *copy(node *t);

nodeth *locate(char ch,nodeth *root);

nodeth *inorderthing(nodeth *sroot);

nodeth *leftest(nodeth *t);

void previsit(nodeth *root);

void invisit(nodeth *droot);

void postvisit(nodeth *droot);

int main() //

讀入使用者輸入的一串先序遍歷字串,根據此字串建立乙個二叉樹

case2:

case3:

case4:

case5:

case6:

case7:

case8:

case9:

case10:

else

break

; }

case11:

else

break

; }

case12:

else

break

; }

case13:

case14:

case15:

default

:

}printf(

"please input your choice:");

scanf("%d

",&choice);

}return0;

}node *contree1()

else

returnp;}

void printbtree(node *t)

printbtree(t->right);

printf(")

");}

}return;}

void preorder(node *t)

}void inorder(node *t)

}void postorder(node *t)

}void npreorder(node *t)

if(top != -1

)

}}void ninorder(node *t)

if(top != -1

)

}}void npostorder(node *t)

while(top != -1 && stk[top].flag == 2

)

if (top != -1

)

}}void leverorder(node *t)

}void inorderth(nodeth *root)

pre =root;

inorderth(root->right);

}}nodeth *inorderthing(nodeth *sroot)

nodeth *leftest(nodeth *t)

return

temp;

}void printbtreeth(nodeth *t) //

輸出線索二叉樹

printbtreeth(t->right);

printf(")

");}

}return;}

nodeth* copy(node *t)

nodeth *prenext(nodeth *p)

if(p->ltag == 1

)

else

q = q->right;

}returnq;}

nodeth *innext(nodeth *p)

}returnq;}

nodeth *locate(char ch,nodeth *root)}}

while(temp !=null);

return

null;

}void previsit(nodeth *root)

}void invisit(nodeth *droot)

}while(temp !=null);

}

樹的建立與層次遍歷

include include include include using namespace std typedef struct treenode treenode treenode bulidtree 普通建立一棵樹 根左右 else return t treenode bulidtreea ...

樹堆的建立與遍歷

l2 011 玩轉二叉樹 25 分 給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裡假設鍵值都是互不相等的正整數。輸入第一行給出乙個正整數n 30 是二叉樹中結點的個數。第二行給出其中序遍歷序列。第三行給出...

資料結構 二叉樹的遍歷與建立

所有節點都只有左子樹的稱為左斜樹 在一棵二叉樹中,如果所有分支節點都存在左子樹和右子樹,並且所有 葉子都在同一層上 這樣的二叉樹被稱為滿二叉樹。二叉樹的建立 struct node node createbinarytree node node return node 前序,後序,中序,層序遍歷 v...