二叉樹給出兩種遍歷序列(含中序遍歷)建立一顆先序遍歷二叉樹
阿新 • • 發佈:2019-01-27
#include <iostream> #include <cstdio> #include <queue> #include <stack> #include <cstring> using namespace std; typedef struct NODE{ NODE() :key('0'), lchild(NULL), rchild(NULL){} char key; NODE *lchild; NODE *rchild; } Node; void pre_mid(Node *&node, int len, char *pre, char *mid){ if(len <= 0) return; node = new Node(); node->key = *pre; char *pm = strchr(mid, *pre); int l_len = pm - mid; int r_len = len - l_len - 1; pre_mid(node->lchild, l_len, pre+1, mid); pre_mid(node->rchild, r_len, pre+l_len+1, pm+1); } void mid_after(Node *&node, int len, char *mid, char *after){ if(len <= 0) return; node = new Node(); node->key = *(after+len-1); char *pm = strchr(mid, node->key); int l_len = pm - mid; int r_len = len - l_len - 1; mid_after(node->lchild, l_len, mid, after); mid_after(node->rchild, r_len, pm+1, after+l_len); } void preorder(Node *node){ if(node == NULL) return; stack<Node *> st; st.push(node); while(!st.empty()){ Node *cur = st.top(); st.pop(); cout << cur->key; if(cur->rchild) st.push(cur->rchild); if(cur->lchild) st.push(cur->lchild); } cout << endl; } void midorder(Node *node){ if(node == NULL) return; stack<Node *> st; Node *cur = node; while(cur || !st.empty()){ while(cur){ st.push(cur); cur = cur->lchild; } if(!st.empty()){ cur = st.top(); st.pop(); cout << cur->key; cur = cur->rchild; } } cout << endl; } typedef struct POINT{ POINT():node(NULL), flag(false){} POINT(Node *_node = NULL, int _flag = false) :node(_node), flag(_flag) {} Node *node; bool flag; } Point; void afterorder(Node *node){ if(node == NULL) return; stack<Point> st; st.push(Point(node, false)); while(!st.empty()){ Point &cur = st.top(); if(cur.flag){ cout << cur.node->key; st.pop(); continue; } if(cur.node->rchild) st.push(Point(cur.node->rchild, false)); if(cur.node->lchild) st.push(Point(cur.node->lchild, false)); cur.flag = true; } cout << endl; } int main() { Node *root = NULL; char *pre = "DBACEGF"; char *mid = "ABCDEFG"; char *after = "ACBFGED"; pre_mid(root, strlen(pre), pre, mid); mid_after(root, strlen(pre), mid, after); preorder(root); midorder(root); afterorder(root); return 0; }