編一個程序,讀入用戶輸入的一串先序遍歷字符串,根據此字符串創建一個二叉樹(以指針方式存儲)。
例如以下的先序遍歷字符串:
ABC##DE#G##F###
其中「#」表示的是空格,空格字符表明空樹。創建起此二叉樹之後,再對二叉樹進行中序遍歷,輸出遍歷結果。html
輸入包括1行字符串,長度不超過100。node
可能有多組測試數據,對於每組數據,
輸出將輸入字符串創建二叉樹後中序遍歷的序列,每一個字符後面都有一個空格。
每一個輸出結果佔一行。ios
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #include <vector> using namespace std; string input; struct node { char data; node * lchild,*rchild; }; void preOrder(node * & root,int & index) { if(index>=input.length()) { return ; } if(input[index]=='#') { root=NULL; index++; } else { root=new node; root->data=input[index]; index++; preOrder(root->lchild,index); preOrder(root->rchild,index); } } void inOrder(node * root) { if(root==NULL) { return ; } inOrder(root->lchild); cout<<root->data<<" "; inOrder(root->rchild); } int main() { while(cin>>input) { node * root=NULL; int index=0; preOrder(root,index); inOrder(root); cout<<endl; } }