1. 程式人生 > >牛客網———二叉樹遍歷

牛客網———二叉樹遍歷

題目描述

編一個程式,讀入使用者輸入的一串先序遍歷字串,根據此字串建立一個二叉樹(以指標方式儲存)。 例如如下的先序遍歷字串: ABC##DE#G##F### 其中“#”表示的是空格,空格字元代表空樹。建立起此二叉樹以後,再對二叉樹進行中序遍歷,輸出遍歷結果。
連結:https://www.nowcoder.com/questionTerminal/4b91205483694f449f94c179883c1fef
來源:牛客網

#include <iostream>
#include <string>
#include <stack>
using
namespace std; int main() { string pre; while(cin >> pre){ stack<char> s; for(auto it : pre){ if(it != '#') s.push(it); else{ if(!s.empty()){ cout << s.top() << ' '; s.pop(); } } } cout
<< '\n'; } }