说明
多行数据
每行一个整数
输入为#时结束数据输入
示例输入
9
5
#
示例输出
非递归
8 4 9 2 5 1 6 3 7
递归
8 4 9 2 5 1 6 3 7
非递归
4 2 5 1 3
递归
4 2 5 1 3
代码
#include <bits/stdc++.h>
using namespace std;
struct Tree
{
int data;
Tree *left;
Tree *right;
Tree(int value) : data(value), left(nullptr), right(nullptr){};
};
Tree *CreateTree(int n)
{
if (n < 1)
return nullptr;
Tree *root = new Tree(1);
queue<Tree *> q;
q.push(root);
int i = 2;
while (!q.empty() && i <= n)
{
Tree *node = q.front();
q.pop();
if (i <= n)
{
node->left = new Tree(i);
q.push(node->left);
}
i++;
if (i <= n)
{
node->right = new Tree(i);
q.push(node->right);
}
i++;
}
return root;
}
// 递归中序打印
void inorderTraversal(Tree *root)
{
if (root != nullptr)
{
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
}
// 非递归中序打印
void inorderTraversal_no(Tree *root)
{
stack<Tree *> st;
Tree *node = root;
while (!st.empty() || node != nullptr)
{
while (node != nullptr)
{
st.push(node);
node = node->left;
}
node = st.top();
st.pop();
cout << node->data << " ";
node = node->right;
}
}
int main()
{
string str;
while (getline(cin, str))
{
if (str == "#")
break;
istringstream iss(str);
int n;
iss >> n;
Tree *test = CreateTree(n);
cout << "非递归\n";
inorderTraversal_no(test);
cout << "\n递归\n";
inorderTraversal(test);
cout << '\n';
}
return 0;
}