二叉树与二叉排序树的创建
创建二叉树
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left,*right; }; /*void preOrderTraverse(TreeNode *p) { if(p) { cout<<p->val<<" "; preOrderTraverse(p->left); preOrderTraverse(p->right); } }*/ void create(TreeNode *&p) { int k; cin>>k; if(k!=0) { p=new TreeNode; p->val=k; create(p->left); create(p->right); } else p=NULL; } int main() { TreeNode *root=NULL; create(root); //preOrderTraverse(root); }
创建二叉排序树
#include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left,*right; }; void Insertnode(TreeNode *&p,int k) { if(p==NULL) { p=new TreeNode; p->val=k; p->left=p->right=NULL; return; } /*if(k==p->val) BST中不能有相等的值 return;*/ if(k<p->val) Insertnode(p->left,k); else Insertnode(p->right,k); } /*void CreateTree(TreeNode *root,int a[],int n) { root=NULL; int i; for(i=0;i<n;i++) { Insertnode(root,a[i]); } }*/ void preOrderTraverse(TreeNode *p) { if(p) { cout<<p->val<<" "; preOrderTraverse(p->left); preOrderTraverse(p->right); } } int main() { int a[]={5,7,1,3,9,2,0,4,8,6}; int i,n=10; TreeNode *root=NULL; for(i=0;i<n;i++) Insertnode(root,a[i]); preOrderTraverse(root); cout<<endl; return 0; }