BST(二叉搜索樹)的基本知識

比較簡單來講的話,BST就是根結點的左子樹所有的結點值都要小於根結點的值
根結點右子樹所有結點的值都要大於根結點的值
比較重要的就是插入和創建樹和查找,其中創建樹是通過查找來實現的
其餘的操作都和普通的二叉樹差不多

#include <bits/stdc++.h>
using namespace std;


struct node
{
	int val;
	node* lchild;
	node* rchild;
	node(int a)
	{
		val=a;
		lchild=NULL;
		rchild=NULL;
	}
	node()
	{
		val=0;
		lchild=NULL;
		rchild=NULL;
	}
};

void insert(node*& root,int x)
{
	if(root==NULL)
	{
		root=new node(x);
		return ;
	}
	if(x==root->val)//在創建的時候這樣可以確保不會重複,當然可以不要,根據具體的題目而定 
	{
		return ;
	}
	else if(x<root->val)
	{
		insert(root->lchild,x);
	}
	else
	{
		insert(root->rchild,x);
	}
}

node* createTree(int data[],int n)
{
	node* root=NULL;
	for(int i=0;i<n;i++)
	{
		insert(root,data[i]);
	}
	return root;
} 

void inOrder(node* root)
{
	if(root==NULL)
	{
		return;
	}
	inOrder(root->lchild);
	cout<<root->val<<" ";
	inOrder(root->rchild);
}

void search(node* root,int x)//和插入差不多
{
	if(root==NULL)
	{
		cout<<x<<" search failed"<<endl;
		return ;
	}
	if(x==root->val)
	{
		cout<<root->val;
	}
	else if(x<root->val)
	{
		search(root->lchild,x);	
	}
	else
	{
		search(root->rchild,x);
	}
}


int main()
{
	int data[10]={1,2,3,4,5,6,7,8,9,0};
	int n=10;
	node* root=createTree(data,n);
	inOrder(root);
	cout<<endl;
	search(root,9);
	cout<<endl;
	search(root,10);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章