带自建树的解法
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int val) : val(val), left(nullptr), right(nullptr) {}
};
void createTree(TreeNode* root, int& n){
if(n==0)
return;
int root_val, l, r;
cin>>root_val>>l>>r;
if(l!=0){
root->left = new TreeNode(l);
createTree(root->left, --n);
}
if(r!=0){
root->right = new TreeNode(r);
createTree(root->right, --n);
}
}
string treeOrderList(TreeNode* root){
if(root==nullptr){
return "#!";
}
string str = to_string(root->val) + "!";
str += treeOrderList(root->left);
str += treeOrderList(root->right);
return str;
}
string treeLevelOrder(TreeNode* root){
if(root==nullptr)
return "#!";
queue<TreeNode*> que;
que.push(root);
string str;
while(!que.empty()){
TreeNode* cur = que.front();
que.pop();
if(cur==nullptr){
str += "#!";
}else{
str += to_string(cur->val) + "!";
que.push(cur->left);
que.push(cur->right);
}
}
return str;
}
int main(){
int n, root_val;
cin>>n>>root_val;
TreeNode* root = new TreeNode(root_val);
createTree(root, n);
string ans1 = treeOrderList(root);
cout << ans1 << endl;
string ans2 = treeLevelOrder(root);
cout << ans2 << endl;
return 0;
}