二叉树,多元树的建立和遍历
多元树没有中序遍历
在建立多元树的时候因为不知道每个结点,有多少个儿子,所以比较麻烦。
这里使用了孩子兄弟法。
就是将二叉树的左右儿子指针,指向逻辑大儿子和第一个兄弟,而后便成了二叉树。
#include<stdio.h> #include<string.h> struct tree { int node; tree * firstson; tree * nextbrother; }; void buildtree(tree *&root) //先序建立多元树 { int ch; scanf("%d",&ch); if(ch==0) { root=NULL; return ; } root=new tree; //申请空间 root->node=ch; buildtree(root->firstson); //遍历逻辑大儿子 buildtree(root->nextbrother); //遍历兄弟 } void Preordertree(tree *root) //先序遍历 { //根->大儿子树先序遍历->二儿子树先序遍历->...->n儿子树先序遍历 if(root==NULL) return; printf("%d ",root->node); Preordertree(root->firstson); //遍历逻辑大儿子 Preordertree(root->nextbrother); //遍历兄弟 } void Postordertree(tree *root) //后序遍历 { //大儿子后序遍历->根->二儿子后序遍历->...->n儿子后序遍历 if(root==NULL) return; Postordertree(root->firstson); //遍历逻辑大儿子 printf("%d ",root->node); Postordertree(root->nextbrother); //遍历兄弟 } int main() { tree *root; printf("先序建立多元树 "); buildtree(root); printf("先序遍历: "); Preordertree(root); printf(" 后序遍历: "); Postordertree(root); printf(" "); }
二叉树
#include<stdio.h> #include<string.h> struct tree { int node; tree *left; tree *right; }; void buildtree(tree *&root) //先序建立二叉树 { int ch; scanf("%d",&ch); if(ch==0) { root=NULL; return; } root=new tree; //申请空间 root->node=ch; buildtree(root->left); //建立左儿子 buildtree(root->right); //建立右儿子 } void Preordertree(tree *root) //先序遍历 {//根->左->右 if(root==NULL) return; printf("%d ",root->node); //输出根 Preordertree(root->left); //遍历左儿子 Preordertree(root->right);//遍历右儿子 } void Inordertree(tree *root) //中序遍历 { //左->根->右 if(root==NULL) return; Inordertree(root->left); printf("%d ",root->node); Inordertree(root->right); } void Postordertree(tree *root) //后序遍历 { //左->右->根 if(root==NULL) return; Postordertree(root->left); Postordertree(root->right); printf("%d ",root->node); } int main() { tree *root; printf("先序输入二叉树: "); buildtree(root); printf(" 先序遍厉: "); Preordertree(root); printf(" 中序遍历: "); Inordertree(root); printf(" 后序遍历: "); Postordertree(root); }