template <class T> struct Node { T data; Node *left; Node *right; Node() : data(), left(NULL), right(NULL) {} }; template <class T, class Iter> void creat_tree(Node<T> *&head, const Iter pre_begin, const Iter pre_end, const Iter in_begin) { if (pre_begin == pre_end) { head = NULL; return ; } const Iter in_end = in_begin + (pre_end - pre_begin); head = new Node<T>(); head->data = *pre_begin; const Iter in_middle = find(in_begin, in_end, *pre_begin); const Iter left_in_begin = in_begin; const Iter left_in_end = in_middle; const Iter left_pre_begin = pre_begin + 1; const Iter left_pre_end = left_pre_begin + (left_in_end - left_in_begin); creat_tree(head->left, left_pre_begin, left_pre_end, left_in_begin); const Iter right_in_begin = in_middle + 1; const Iter right_in_end = in_end; const Iter right_pre_begin = left_pre_end; const Iter right_pre_end = pre_end; creat_tree(head->right, right_pre_begin, right_pre_end, right_in_begin); } template <class T> void alter_order(Node<T> *&root) { if (NULL == root) { return ; } alter_order(root->left); alter_order(root->right); } template <class T> void input (vector<T> &v, int size) { T value; while(size--) { cin >> value; v.push_back(value); } } template <class T> void BFS (Node<T> *&root) { queue < Node<T>* > Q; Q.push (root); while (!Q.empty ()) { Node<T>* cur = Q.front (); Q.pop (); if (cur == root) cout << root->data; else cout << ' ' << cur->data; if (cur->left != NULL) Q.push (cur->left); if (cur->right != NULL) Q.push (cur->right); } }
已知前序中序 求层次遍历