【数据结构】二叉搜索树——转换成有序双向链表

本文介绍如何将二叉搜索树转换为有序的双向链表。通过中序遍历的方法,调整节点间的指针指向,使得最终的结构符合双向链表的特点,即每个节点都有指向其前驱和后继的指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上一篇博客中,我们对二叉搜索树已经有了简单的认识。下面我们看看怎样将二叉搜索树转换成有序的双向链表

在二叉搜索树中,左子树结点的值小于双亲结点的值,右子树结点的值大于双亲结点的值。在双向链表中,每个结点也有两个指针,分别指向前一个结点和后一个结点。因此我们可以通过改变指针指向将二叉搜索树转换成双向链表。



具体实现代码如下:

#pragma once
#include <iostream>
using namespace std;
template <class K, class V>
struct BSTreeNode
{
	BSTreeNode(const K& key, const V& value)
	: _key(key)
	, _value(value)
	, _pLeft(NULL)
	, _pRight(NULL)
	, _pParent(NULL)
	{}
	BSTreeNode<K, V>* _pLeft;
	BSTreeNode<K, V>* _pRight;
	BSTreeNode<K, V>* _pParent;
	K _key;
	V _value;
};

template <class K, class V>
class BSTree
{
	typedef BSTreeNode<K, V> Node;
	typedef Node* pNode;
public:
	BSTree()
		: _pRoot(NULL)
	{}

	bool Insert(const K& key, const V& value)//非递归插入
	{
		if (NULL == _pRoot)
		{
			_pRoot = new Node(key, value);
			return true;
		}
		pNode pCur = _pRoot;
		pNode pParent = NULL;
		while (pCur)
		{
			pParent = pCur;
			if (key < pCur->_key)
				pCur = pCur->_pLeft;
			else
				pCur = pCur->_pRight;
		}
		pCur = new Node(key, value);
		if (key < pParent->_key)
			pParent->_pLeft = pCur;
		else if (key > pParent->_key)
			pParent->_pRight = pCur;
		else
			return false;
		pCur->_pParent = pParent;
		return true;
	}

	pNode BSTreeToList()
	{
		if (NULL == _pRoot)
			return NULL;
		pNode pHead = _pRoot;//定义链表的头结点
		while (pHead->_pLeft)
			pHead = pHead->_pLeft;
		pNode prev = NULL;
		_BSTreeToList(_pRoot, prev);
		return pHead;
	}
private:
	void _BSTreeToList(pNode pRoot, pNode& prev)
	{
		if (NULL == pRoot)
			return;
		_BSTreeToList(pRoot->_pLeft, prev);
		pRoot->_pLeft = prev;
		if (prev)
			prev->_pRight = pRoot;
		prev = pRoot;
		_BSTreeToList(pRoot->_pRight, prev);
	}
private:
	pNode _pRoot;
};

void Test()
{
	int arr[] = { 5, 3, 4, 1, 2, 0 };
	BSTree<int, int> bt;
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
		bt.Insert(arr[i], arr[i]);
	BSTreeNode<int, int>* pNode = bt.BSTreeToList();
	BSTreeNode<int, int>* pCur = pNode;
	while (pCur)//正向打印
	{
		cout << pCur->_key << " ";
		pCur = pCur->_pRight;
	}
	cout << endl;
	
	pCur = pNode;//逆向打印
	while (pCur->_pRight)
		pCur = pCur->_pRight;
	while (pCur)
	{
		cout << pCur->_key << " ";
		pCur = pCur->_pLeft;
	}
}
测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值