提交时间:2023-08-23 20:23:26
运行 ID: 99800
#include <bits/stdc++.h> using namespace std; struct tree{ int val; tree *left; tree *right; }; int arr[105]; void digui(tree*s,vector<int>&z){ if(s!=nullptr){ z.push_back(s->val); digui(s->left,z); digui(s->right,z); } } int main(){ int n; tree* root = nullptr; cin>>n; for(int i = 1;i<=n;i++){ cin>>arr[i]; } root = new(tree); root->val = arr[1]; root->left = nullptr; root->right = nullptr; tree *node, *ptr; for(int i = 2;i<=n;i++){ ptr = new(tree); ptr->val = arr[i]; ptr->left = nullptr; ptr->right = nullptr; node = root; while(node!=nullptr){ if (arr[i] < node->val) { if (node->left == nullptr) { node->left = ptr; break; } node = node->left; } else { if (node->right == nullptr) { node->right = ptr; break; } node = node->right; } } } vector<int> ans; digui(root,ans); for(int i = 0;i<ans.size();i++){ cout<<ans[i]<<" "; } cout<<endl; return 0; }