把二元查找树转变成排序的双向链表(微软面试题)

参考了July的博客,然后自己动手实现了一线,留着备忘吧!


题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
    
    10
    / \
   6  14
  / \ / \
4  8 12 16
    
  转换成双向链表
  4=6=8=10=12=14=16。

实现如下:

#include <iostream>
#include <cstdio>
using namespace std;

struct BSTreeNode  //存储二叉查找树节点信息
{
	int val;
	BSTreeNode *lchild,*rchild;
}; 

typedef BSTreeNode DoubleList; 

DoubleList *pHead,*pLastIndex; //pHead存储头节点,pLaseIndex存储上一个插入的节点

//中序序列创建二叉查找树
void CreateBSTree(BSTreeNode * & pCurrent,int val)  //pCurrent是一个BSTreeNode*类型的引用
{
	if(NULL == pCurrent)
	{
		BSTreeNode *temp=new BSTreeNode() ;
		temp->val = val ;
		temp->lchild = NULL , temp->rchild = NULL ;
		pCurrent = temp ;  
	}
	else
	{
		if(pCurrent->val > val)
			CreateBSTree(pCurrent->lchild,val);
		else if(pCurrent->val < val)
			CreateBSTree(pCurrent->rchild,val);
		else cout<<"输入数据重复"<<endl;
	}
}

void ConvertToDoubleList(BSTreeNode *node);  //将二叉树转换为双向链表

//中序遍历二叉查找树
void InorderBSTree(BSTreeNode *pCurrent)
{
	if(pCurrent == NULL) return;
	if(pCurrent->lchild != NULL)
		InorderBSTree(pCurrent->lchild);
	ConvertToDoubleList(pCurrent);
	if(pCurrent->rchild != NULL)
		InorderBSTree(pCurrent->rchild);
}

void ConvertToDoubleList(BSTreeNode *node)
{
	node->lchild = pLastIndex ;
	if(pLastIndex == NULL)
		pHead = node ;
	else
		pLastIndex->rchild = node ;
	pLastIndex = node ;  
	cout<<" "<<node->val<<endl;  
}

int main()
{
	BSTreeNode *pRoot ;
	pRoot = pHead = pLastIndex = NULL ;
	CreateBSTree(pRoot,4);
	CreateBSTree(pRoot,10); 
	CreateBSTree(pRoot,6);
	CreateBSTree(pRoot,16);
	CreateBSTree(pRoot,14);
	CreateBSTree(pRoot,12);
	CreateBSTree(pRoot,8);
	InorderBSTree(pRoot); 
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值