提交时间:2023-08-23 21:35:29
运行 ID: 99822
#include<bits/stdc++.h> using namespace std; struct TreeNode { int data; TreeNode* leftChild; TreeNode* rightChild; TreeNode(int x):data(x),leftChild(nullptr),rightChild(nullptr){} }; void PreOrder(TreeNode* root) { if(root==nullptr) { return ; } cout<< root->data; cout<<" "; PreOrder(root->leftChild); PreOrder(root->rightChild); } TreeNode* Build(TreeNode* root,int x) { if(root==nullptr) { root=new TreeNode(x); } else if(x < root->data) { root->leftChild=Build(root->leftChild,x); } else if(x > root->data) { root->rightChild=Build(root->rightChild,x); } return root; } TreeNode* root=nullptr; int main() { int n; int x; cin>>n; while(n--) { cin>>x; root=Build(root,x); } PreOrder(root); return 0; }