想法:分治,根据前序遍历来对中序遍历进行划分,分为左右子树
/* * test.cpp * * Created on: Dec 13, 2010 * Author: alfred */ #include <iostream> #include <string> using namespace std; struct node { char data; node* left; node* right; node(char data = '/0', node* left = NULL, node* right = NULL) { this->data = data; this->left = left; this->right = right; } }; void build_left(int, int, node*); void build_right(int, int, node*); int cur; string pre_tra, inorder_tra; int main() { node root; while(cin >> pre_tra >> inorder_tra) { root.data = pre_tra[0]; cur = 1; int pos = inorder_tra.find(pre_tra[0]); build_left(0, pos - 1, &root); build_right(pos + 1, inorder_tra.size(), &root); post_tra(&root); } return 0; } void build_left(int beg, int end, node* parent) { if(beg > end || cur >= pre_tra.size()) return; parent->left = new node(pre_tra[cur]); int pos = inorder_tra.find(pre_tra[cur]); cur++; build_left(beg, pos - 1, &(*parent->left)); build_right(pos + 1, end, &(*parent->left)); } void build_right(int beg, int end, node* parent) { if(beg > end || cur >= pre_tra.size()) return; parent->right = new node(pre_tra[cur]); int pos = inorder_tra.find(pre_tra[cur]); cur++; build_left(beg, pos- 1, &(*parent->right)); build_right(pos + 1, end, &(*parent->right)); }
本文介绍了一种使用前序遍历和中序遍历来构建二叉树的方法。通过递归地划分中序遍历序列来确定每个节点的位置,并以此构建完整的二叉树结构。
2158

被折叠的 条评论
为什么被折叠?



