复习下BST( Binary search tree)

     Binary search tree的遍历分为preorder traversal、inorder traversal、postorder traversal三种。

树节点的结构如下:

struct node
{
 int sum;
 string name;
 struct node *left,*right;
};


 

preorder traversal递归遍历:

void preprint(*root)
{
if(root!=NULL){
preprint(root->left);
visit(root);
preprint(root->right);
}
} 

改为不递归遍历:

void preOrder1(TNode* root)
{
Stack S;
while ((root != NULL) || !S.empty())
{
if (root != NULL)
{
  Visit(root);
  S.push(root); // 先序就体现在这里了,先访问,再入栈
  root = root->left; // 依次访问左子树
}
else
{
   root = S.pop(); // 回溯至父亲节点
   root = root->right;
}
}
}

构建Binary  search tree还有一个最重要的函数便是插入节点函数的写法,结合pojhttp://poj.org/problem?id=1002题目:

void insert(string t,node *p)
{
	if(p->name==t)
	{
		p->sum++;
		return ;
	}
	int y=t.compare(p->name);
	if(y>0)
	{
		if(p->right==NULL)
		{
			p->right=new node;
			p->right->right=p->right->left=NULL;
			p->right->sum=1;
			p->right->name=t;
		}
		else insert(t,p->right);
	}
	else
	{
		
		if(p->left==NULL)
		{
			p->left=new node();
			p->left->right=p->left->left=NULL;
			p->left->sum=1;
			p->left->name=t;
		}
		else insert(t,p->left);
	}
}

在main函数中,先定义根节点,再依次插入相应的节点。:

	          node *h;
		h=new node();
		h->sum=1;
		h->right=h->left=NULL;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值