您的位置:首页 > 职场人生

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

2018-03-16 14:00 495 查看

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

题目:

输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。

要求不能创建任何新的结点,只调整指针的指向。

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

38

BSTreeNode *m_pRight; // right child of node

};

代码如下

template<typename T>
struct TreeNode
{
T data;
TreeNode* pLChild;
TreeNode* pRChild;
};

// 要求两个输出参数要初始化为NULL
template<typename T>
void ConvertBSTree2List(TreeNode<T>* pTreeRoot/*树的根节点*/, TreeNode<T>*& pListHead/*双向链表的头指针*/, TreeNode<T>*& pListLast/*双向链表的尾指针*/)
{
if(pTreeRoot == NULL)
{
return;
}

ConvertBSTree2List(pTreeRoot->pLChild, pListHead, pListLast);

if(pListLast)
{
pTreeRoot->pLChild = pListLast;
pListLast->pRChild = pTreeRoot;
pListLast = pTreeRoot;
}
else
{
pListHead = pListLast = pTreeRoot;
pTreeRoot->pLChild = NULL;

}

ConvertBSTree2List(pTreeRoot->pRChild, pListHead, pListLast);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐