二叉排序树
Posted fzuhyj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉排序树相关的知识,希望对你有一定的参考价值。
#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; struct BSTNode{ int val; BSTNode* left; BSTNode* right; BSTNode* parent; }; bool insert(BSTNode* &root, BSTNode* node){ BSTNode* t = root; BSTNode* temp = NULL; while(t!=NULL){ temp = t; if(node->val<t->val){ t = t->left; }else if(node->val>t->val){ t = t->right; }else{ return false; } } node->parent = temp; if (temp == NULL){ root = node; }else if(node->val < temp->val){ temp->left = node; }else if(node->val > temp->val){ temp->right = node; }else{ return false; } return true; } void preOrder(BSTNode* root){ if (root != NULL){ cout<<root->val<<" "; preOrder(root->left); preOrder(root->right); } } void inOrder(BSTNode* root){ if (root != NULL){ inOrder(root->left); cout<<root->val<<" "; inOrder(root->right); } } void postOrder(BSTNode* root){ if (root != NULL){ postOrder(root->left); postOrder(root->right); cout <<root->val<<" "; } } int main(){ int n; while(scanf("%d",&n)!=EOF){ BSTNode* root; for(int i=0;i<n;i++){ BSTNode* node = (BSTNode*)malloc(sizeof(BSTNode)); cin>>node->val; node->left = NULL; node->right = NULL; node->parent = NULL; if(i == 0){ root = node; }else{ insert(root,node); } } preOrder(root); cout<<endl; inOrder(root); cout<<endl; postOrder(root); cout<<endl; } return 0; }
以上是关于二叉排序树的主要内容,如果未能解决你的问题,请参考以下文章