题解 | #二叉排序树#基本做法
二叉排序树
https://www.nowcoder.com/practice/b42cfd38923c4b72bde19b795e78bcb3
#include <iostream> using namespace std; struct BTree { int val; struct BTree*lchild,*rchild; BTree(int x):val(x),lchild(nullptr),rchild(nullptr){}; }; void createBTree(BTree *&root,int n) { if(root==nullptr) root=new BTree(n); else if(n>root->val) createBTree(root->rchild, n); else if(n<root->val) createBTree(root->lchild, n); } void preOrder(BTree*root) { if(root) { cout<<root->val<<" "; preOrder(root->lchild); preOrder(root->rchild); } } void inOrder(BTree*root) { if(root) { inOrder(root->lchild); cout<<root->val<<" "; inOrder(root->rchild); } } void postOrder(BTree*root) { if(root) { postOrder(root->lchild); postOrder(root->rchild); cout<<root->val<<" "; } } int main() { int n; int t; while(cin>>n) { BTree*T=nullptr; for(int i=0;i<n;i++) { cin>>t; createBTree(T,t); } preOrder(T); cout<<endl; inOrder(T); cout<<endl; postOrder(T); cout<<endl; } return 0; } // 64 位输出请用 printf("%lld")