二叉树的操作(二叉树的创建、先序遍历---先根、中序遍历----先左、后续遍历---后根)
生活随笔
收集整理的這篇文章主要介紹了
二叉树的操作(二叉树的创建、先序遍历---先根、中序遍历----先左、后续遍历---后根)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include "stdlib.h"
#include "stdio.h"
#include "Windows.h"
#include <algorithm>
using namespace std; /*引入頭文件*/
struct tnode /*定義二叉樹存儲結構*/
{char data;struct tnode*lchild;struct tnode*rchild;
};
struct tnode tree; /*定義二叉樹指針*/void createtree(struct tnode*t) /*創建函數*/
{struct tnode*p=t; /*把二叉樹指針給p*/char check;if(p->lchild==NULL||p->rchild==NULL) /*判斷左右子樹是否為空*/{printf("please enter the data:"); /*輸入根結點數據*/scanf("%c",&(p->data));getchar();}if(p->lchild==NULL){printf("%c leftchild is null.Add? y/n\n",p->data); /*左子樹空,詢問是否創建*/scanf("%c",&check);getchar();if(check=='y'){struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*開辟空間*/q->lchild=NULL;q->rchild=NULL;p->lchild=q;createtree(q);}}if(p->rchild==NULL) {printf("%c rightchild is NULL.Add? y/n\n",p->data); /*右子樹空,詢問是否創建*/scanf("%c",&check);getchar();if(check=='y'){struct tnode*q=(struct tnode*)malloc(sizeof(struct tnode)); /*開辟空間*/q->lchild=NULL;q->rchild=NULL;p->rchild=q; /*連到二叉樹上*/createtree(q);}}
}void preorder(struct tnode*t) /*先序遍歷函數*/
{if(t){printf("%c ",t->data); /*輸出根結點數據*/preorder(t->lchild);preorder(t->rchild);}
}void inorder(struct tnode*t) /*中序遍歷函數*/
{if(t){inorder(t->lchild);printf("%c ",t->data);inorder(t->rchild);}
}
void postorder(struct tnode*t) /*后序遍歷函數*/
{if(t){postorder(t->lchild);postorder(t->rchild);printf("%c ",t->data);}
}void main()
{//clrscr(); /*清屏函數*/tree.lchild=NULL; /*左子樹*/tree.rchild=NULL; /*右子樹*/createtree(&tree); /*創建二叉樹*/preorder(&tree); /*先序遍歷*/printf("\n");inorder(&tree); /*中序遍歷*/printf("\n");postorder(&tree); /*后序遍歷*/
}
總結
以上是生活随笔為你收集整理的二叉树的操作(二叉树的创建、先序遍历---先根、中序遍历----先左、后续遍历---后根)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 彭荣新:喜马拉雅自研网关架构演进过程
- 下一篇: 忽悠CTO搞中台,把自己饭碗都搞砸了