二叉树的遍历 同类题型:1078
笨办法直接建树:
#include <cstdio> #include <cstring> char str[105]; struct Node { Node *lChild; Node *rChild; char d; } Tree[105]; int pos; int cur; Node* BuildTree(int e) { if (str[cur] == ‘#‘ || cur >= e) return NULL; Tree[pos].lChild = Tree[pos].rChild = NULL; Node* root = &Tree[pos++]; root->d = str[cur]; ++cur; root->lChild = BuildTree(e); ++cur; root->rChild = BuildTree(e); return root; } void PrintTree(const Node* rt) { if(rt == NULL) return; if(rt->lChild != NULL) PrintTree(rt->lChild); printf("%c ", rt->d); if(rt->rChild != NULL) PrintTree(rt->rChild); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif while (scanf("%s", str) != EOF) { pos = 0; cur = 0; Node* rt = BuildTree(strlen(str)); PrintTree(rt); printf("\n"); } return 0; }
或者直接模拟:
原文:http://www.cnblogs.com/fripside/p/3567186.html