微软面试题<一>

题目:

把二叉查找树变成排序后的双向链表.

             10

             /    \

           6     14

        /     \   /    \

      4     8 12 16

得到 4=6=8=10=12=14=16

思路:

 由于对二叉查找树的中序遍历就会得到一个排序后的数组。

所以可以在中序遍历时对每个遍历的结点进行构建双向链表(注意不是循环链表),每次对遍历的结点进行插入操作,最终得到结果。代码如下:

#include <iostream>
using namespace std;
struct BinarySearchTreeNode
{
	int data;
	BinarySearchTreeNode *left,*right;
};
typedef BinarySearchTreeNode DoubleList;
DoubleList *head=NULL,*tail=NULL;  //双向链表头尾指针
//利用依次插入结点构造二叉查找树
void InsertNode(BinarySearchTreeNode *&root,int key)
{
	if(!root)
	{
		BinarySearchTreeNode *newnode=new BinarySearchTreeNode;
		newnode->left=newnode->right=NULL;
		newnode->data=key;
		root=newnode;
	}
	else
	{
		if(key<root->data)
		InsertNode(root->left,key);
		else if(key>root->data)
		InsertNode(root->right,key);
		else if(key==root->data)
		cout<<"树中已有该结点"<<endl;
	}
}

void Convert(DoubleList *cur)
{
	if(!tail)
	{
		head=cur;
		cur->left=tail; 
	}
	else
	{
		cur->left=tail;
		tail->right=cur;
	}
	tail=cur;
}
//中序遍历二叉查找树
void PostOrder(BinarySearchTreeNode *root)
{
	if(root)
	{
		PostOrder(root->left);
		Convert(root);
		PostOrder(root->right);
	}
}

int main()
{
	int a[7]={10,6,8,4,12,14,16};
	BinarySearchTreeNode *root=new BinarySearchTreeNode;
	root=NULL;
	for(int i=0;i<7;++i)
	InsertNode(root,a[i]);
	PostOrder(root);
	while (head!=NULL)  //从前往后的次序
	{
		cout<<head->data<<" ";
		head=head->right;
	}
	cout<<endl;
	while (tail!=NULL)  //从后往前的次序
	{
		cout<<tail->data<<" ";
		tail=tail->left;
	}
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值