牛客网———二叉树遍历

题目描述

编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: 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';  }
}

猜你喜欢

转载自www.cnblogs.com/JAYPARK/p/10061165.html