写一段c++代码,要求如下:【问题描述】编写先序遍历的非递归算法,显示二叉树的先序序列 【输入形式】AB##C## 【输出形式】ABC 【样例输入】AB##C## 【样例输出】ABC
时间: 2023-10-08 11:08:53 浏览: 112
以下是一段基于栈的非递归先序遍历代码:
```c++
#include<iostream>
#include<stack>
using namespace std;
struct TreeNode{
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x):val(x), left(NULL), right(NULL){}
};
void preOrder(TreeNode* root){
if(!root) return;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* cur = s.top();
s.pop();
cout<<cur->val;
if(cur->right) s.push(cur->right);
if(cur->left) s.push(cur->left);
}
}
int main(){
string input;
cin>>input;
TreeNode* root = NULL;
stack<TreeNode*> s;
for(int i=0; i<input.size(); i++){
if(input[i] == '#'){
if(s.empty()) break;
TreeNode* cur = s.top();
s.pop();
if(s.empty()) root = cur;
else{
TreeNode* parent = s.top();
if(parent->left == NULL) parent->left = cur;
else parent->right = cur;
}
}
else{
TreeNode* cur = new TreeNode(input[i]);
s.push(cur);
}
}
preOrder(root);
return 0;
}
```
输入样例:
```
AB##C##
```
输出样例:
```
ABC
```
阅读全文