題目描述
編一個程序,讀入用戶輸入的一串先序遍歷字符串,根據此字符串建立一個二叉樹(以指針方式存儲)。
例如如下的先序遍歷字符串:
ABC##DE#G##F###
其中“#”表示的是空格,空格字符代表空樹。建立起此二叉樹以后,再對二叉樹進行中序遍歷,輸出遍歷結果。
輸入
輸入包括1行字符串,長度不超過100。
輸出
可能有多組測試數據,對於每組數據,
輸出將輸入字符串建立二叉樹后中序遍歷的序列,每個字符后面都有一個空格。
每個輸出結果占一行。
樣例輸入
a#b#cdef#####a##
樣例輸出
a b f e d c
a
注:每個字母后面跟着一個空格。
分析:與二叉樹復原進行對比,是兩種不同的構建二叉樹的方法。
#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; } }