二叉搜索树变成有序双向链表,要求不能创建新的结点,只调整指针的指向

本文介绍如何通过调整二叉搜索树的指针指向,将二叉搜索树转换为有序双向链表,具体包括寻找链表首结点、中序遍历调整指针、递归处理子树等步骤。

二叉搜索树的结点有2个指针,分别指向左右孩子,双链表的每个结点也有2个指针,分别指向前后结点,所以在不创建新结点,只调整指针指向时可以将二叉搜索树变成双向链表;又由于二叉搜索树在中序遍历时是有序的,所以可以采用中序处理二叉搜索树调整指针指向将其变成有序双向链表。为了简化指针移动操作,我们让左孩子为前向指针,右孩子为后向指针。

二叉搜索树的最左结点即使整个树中最小的结点,所以首先找到最左结点,它就是链表的首结点,链表最后一个结点初始化为空。中序遍历时,当前结点的左孩子指向链表的最后一个结点,若最后一个结点不为空,则最后结点的右孩子指向当前结点,当前结点作为最后一个结点。递归的在所有子树中进行。

#include<iostream>
using namespace std;
class tree_node{
public:
	class tree_node* left,*right;
	int data;
	tree_node(int d,tree_node *l=NULL,tree_node *r=NULL)
	{
		data=d;
		left=l;
		right=r;
	}
};

tree_node* insert_node(tree_node *root,int d)
{
	tree_node *curr=root,*prev;
	while(curr!=NULL)
	{
		prev=curr;
		if(curr->data < d)
		{
			curr=curr->right;
		}
		else
		{
			curr=curr->left;
		}
	}
	if(root==NULL)
	{
		root=new tree_node(d);
	}
	else
	{
		if(prev->data< d)
		{
			prev->right=new tree_node(d);
		}
		else
			prev->left=new tree_node(d);
	}
	return root;
}

void PrintBSTree(tree_node* tree)  
{  
    if(tree==NULL)  
        return;  
    PrintBSTree(tree->left);  
    cout << tree->data << " ";  
    PrintBSTree(tree->right);  
}
tree_node * findLeft(tree_node *root )
{
	if(root==NULL)
		return NULL;
	while (root->left!=NULL)
	{
		root=root->left;
	}
	return root;
}
void convertNode(tree_node *root,tree_node** lastnode)
{
	if(root==NULL)
		return;
	if(root->left!=NULL)
		convertNode(root->left,lastnode);
	root->left=*lastnode;
	if(*lastnode!=NULL)
		(*lastnode)->right=root;
	*lastnode=root;
	if(root->right!=NULL)
		convertNode(root->right,lastnode);

}
tree_node * treeTolist(tree_node *root,tree_node *head,tree_node *lastnode)
{
	if(root==NULL)
		return NULL;
	head=findLeft(root);
	lastnode=NULL;
	convertNode(root,&lastnode);
	return head;
}
void PrintDList(tree_node *h)
{
	tree_node* curr=h;
	while(curr!=NULL)
	{
		cout<<curr->data<<" ";
		curr=curr->right;
	}
}
int main()
{
	tree_node* root=NULL;
	tree_node* DList,*head=NULL,*tail=NULL;
	for(int i=0;i<10;i++)
	{
		int d=rand()%100;
		root=insert_node(root,d);
	}
	cout<<"二叉搜索树:"<<endl;
	PrintBSTree(root);
	head=treeTolist(root,head,tail);
	cout<<endl<<"有序双向链表"<<endl;
	PrintDList(head);
	return 0;
}

  

转载于:https://www.cnblogs.com/woshikafeidouha/p/4166632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值