首页 > 其他 > 详细

二叉树----前序和中序序列得到后序序列

时间:2016-03-29 00:53:47      阅读:207      评论:0      收藏:0      [点我收藏+]

参考:http://www.cnblogs.com/rain-lei/p/3576796.html

输入: preOrder 5 3 2 4 8 6 9  midOrder 2 3 4 5 6 8 9

输出:postOrder 2 4 3 6 9 8 5

#include <iostream>
using namespace std;

const int maxn = 100;

typedef struct Node
{
    int key;
    struct Node *left;
    struct Node *right;
}treeNode;

int preOrder[maxn];
int midOrder[maxn];

// 由中序和后序序列创建树 treeNode
*createTree(int preLeft, int preRight, int midLeft, int midRight) { if (preRight - preLeft < 0) return NULL; treeNode *root = new treeNode; root->key = preOrder[preLeft]; if (preRight == preLeft) { root->left = NULL; root->right = NULL; } int index; for (index = midLeft; index <= midRight; ++index) { if (midOrder[index] == preOrder[preLeft]) break; } root->left = createTree(preLeft + 1, preLeft + (index - midLeft), midLeft, index - 1); root->right = createTree(preLeft + (index - midLeft) + 1, preRight, index + 1, midRight); return root; } void postOrder(treeNode *root) { if (root != NULL) { postOrder(root->left); postOrder(root->right); cout << root->key << " "; } } int main() { int n; cout << "Input the number of Node: " << endl; cin >> n; cout << "The preOrder: " << endl; for (int i = 0; i < n; ++i) cin >> preOrder[i]; cout << "The midOrder: " << endl; for (int i = 0; i < n; ++i) cin >> midOrder[i]; treeNode *root = createTree(0, n - 1, 0, n - 1); cout << "The postOrder: " << endl; postOrder(root); cout << endl; system("pause"); return 0; }

二叉树----前序和中序序列得到后序序列

原文:http://www.cnblogs.com/xuyan505/p/5331149.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!