本文主要是介绍二叉树先序构建+(先序,中序,后序遍历),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/** 样例 DBA,,C,,E,GF,,,*/
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
#define ms(x,y) memset(x,y,sizeof(x))
const int MAXN=1000+10;
const int INF=1<<30;
using namespace std;struct Node
{char ch;Node *left, *right;
};void BuildTree(Node *&root)
{Node *s = (Node *)malloc(sizeof(Node));s->left = NULL;s->right = NULL;scanf("%c", &s->ch);if(s->ch == ','){free(s);return;}root = s;BuildTree(root->left);BuildTree(root->right);
}void PreOrder(Node *root)
{if(root == NULL) return;printf("%c", root->ch);PreOrder(root->left);PreOrder(root->right);
}void InOrder(Node *root)
{if(root == NULL) return;InOrder(root->left);printf("%c", root->ch);InOrder(root->right);
}void PostOrder(Node *root)
{if(root == NULL) return;PostOrder(root->left);PostOrder(root->right);printf("%c", root->ch);
}int main()
{freopen("in.txt","r",stdin);Node *root;BuildTree(root);PreOrder(root);printf("\n");InOrder(root);printf("\n");PostOrder(root);printf("\n");return 0;
}
这篇关于二叉树先序构建+(先序,中序,后序遍历)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!