把二元查找树转变成排序的双向链表

题目:

输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
    10
    /   \
  6    14
 / \      / \
4 8 12 16
转换成双向链表
4 = 6 = 8 = 10 = 12 = 14 = 16。
首先我们定义的二元查找树节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};

我的解法:

中序遍历调整每个节点

只需要将当前结点连接至双向链表的最后一个结点,双向链表的最后一个结点连接至当前结点即可

 

Bst.h
#pragma once

struct BSTreeNode
{
	int m_nValue; // value of node
	BSTreeNode *m_pLeft; // left child of node
	BSTreeNode *m_pRight; // right child of node
};

class Bst
{
public:
	Bst();
	~Bst();

private:
	BSTreeNode* m_pRoot;//树根节点
	BSTreeNode* m_pHead;//指向链表头结点
	BSTreeNode* m_pTail;//指向当前链表最后一个节点

	void Bstinsert(BSTreeNode* &root, int iValue);//创建BST
	void BstToDlist(BSTreeNode * root);//转换
	void changeNode(BSTreeNode* pCurrent);//改变节点指向
	void printDlist(BSTreeNode* head);//输出链表

public:
	void insert(int value);//创建BST
	void change();
	void show();

};

Bst.cpp
#include "Bst.h"
#include<iostream>
using namespace std;

Bst::Bst()
{
	m_pHead = NULL;
	m_pTail = NULL;
	m_pRoot = NULL;
}

Bst::~Bst()
{
}

void Bst::Bstinsert(BSTreeNode *& root, int iValue)
{
	if (NULL == root)
	{
		root = new BSTreeNode();
		root->m_nValue = iValue;
		root->m_pLeft = NULL;
		root->m_pRight = NULL;
	}
	else if (iValue > root->m_nValue)
	{
		Bstinsert(root->m_pRight, iValue);
	}
	else if (iValue < root->m_nValue)
	{
		Bstinsert(root->m_pLeft, iValue);
	}
	else
		cout <<iValue<< "节点已存在"<<endl;
}

void Bst::BstToDlist(BSTreeNode * root)
{
	if (NULL == root)
	{
		return;
	}
	BstToDlist(root->m_pLeft);
	changeNode(root);
	BstToDlist(root->m_pRight);
}

void Bst::changeNode(BSTreeNode * pCurrent)
{
	pCurrent->m_pLeft = m_pTail;//左孩子节点指向当前链表最后一个节点
	if (NULL == m_pTail)
	{
		m_pHead = pCurrent;//创建头结点
	}
	else
	{
		m_pTail->m_pRight;//当前链表最后一个节点的右孩子节点指向当前节点
	}
	m_pTail = pCurrent;//调整m_pTail重新指向当前链表最后一个节点
}

void Bst::printDlist(BSTreeNode * head)
{
	if (head != NULL)
	{
		cout << head->m_nValue << endl;
		printDlist(head->m_pRight);
	}
}


void Bst::insert(int value)
{
	Bstinsert(m_pRoot, value);
}

void Bst::change()
{
	BstToDlist(m_pRoot);
}

void Bst::show()
{
	printDlist(m_pHead);
}

main.cpp
#include<iostream>
#include"Bst.h"
using namespace std;
void main()
{
	Bst BstList;
	BstList.insert(4);
	BstList.insert(6);
	BstList.insert(8);
	BstList.insert(10);
	BstList.insert(12);
	BstList.insert(14);
	BstList.insert(16);
	BstList.change();
	BstList.show();
}



 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值