题解 | #二叉排序树#
二叉排序树
http://www.nowcoder.com/practice/30a0153649304645935c949df7599602
#include<iostream> using namespace std; struct Treenode{ int data; Treenode* leftchild; Treenode* rightchild; Treenode(int c):data(c),leftchild(NULL),rightchild(NULL){} }; Treenode* insert(Treenode* root,int x,int father){ if(root==NULL){ //创建新结点 root=new Treenode(x); cout<<father<<endl; //输出父结点 }else if(root->data>x){ //插入左子树 root->leftchild=insert(root->leftchild,x,root->data); }else{ //插入右子树 root->rightchild=insert(root->rightchild,x,root->data); } return root; } int main(){ int n; while(cin>>n){ Treenode * root=NULL; //建立空树 for(int i=0;i<n;i++){ //逐个插入 int x; cin>>x; root=insert(root,x,-1); } } return 0; }