C/C++生成二叉树并搜索

2015-01-27 10:08:34 · 作者: · 浏览: 9

直接上干货:

#include "targetver.h"
using namespace std;

//定义节点
struct BiNode
{
	int data;
	BiNode * lchild;
	BiNode * rchild;
};
//插入结点
BiNode * InsertBST(BiNode * root,int data)
{
if(root==NULL)
{
	root=new BiNode;
	root->data=data;
	root->lchild =root->rchild =NULL;
}
if(root->data >data)
	root->lchild = InsertBST(root->lchild ,data);
if(root->data 
  
   rchild = InsertBST(root->rchild ,data);
return root;
}
//创建二叉树
BiNode * CreateBST(BiNode * root,int data[],int n)
{
	int i;
	for(i=0;i
   
    data<<"->" ; PrintBST(root->lchild ); PrintBST(root->rchild ); } } int main(int argc, char* *argv) { BiNode * root=NULL; int data[10]={5,9,4,7,3,6,1,8,2,10}; root=CreateBST(root,data,10); PrintBST(root); cout<
    
     
结果(VS2010):