【算法Everyday】第一日 二叉查找树转双向链表

时间:2023-03-10 03:48:51
【算法Everyday】第一日 二叉查找树转双向链表

算法题目链接:http://bbs.csdn.net/topics/350093707

题目

// 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
// BSTreeNode *m_pRight; // right child of node
// };

分析

本质上应该属于二叉树遍历的问题,中序遍历。因为不能创建新的节点,所以只能用递归。

代码

struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
}; BSTreeNode* Convert(BSTreeNode* node, BSTreeNode** nodeHead)
{
if (node->m_pLeft)
{
BSTreeNode* bottomRight = Convert(node->m_pLeft, nodeHead);
bottomRight->m_pRight = node;
node->m_pLeft = bottomRight;
}
else
{
if (!*nodeHead)
{
*nodeHead = node;
}
} if (node->m_pRight)
{
BSTreeNode* bottomRight = Convert(node->m_pRight, nodeHead);
node->m_pRight->m_pLeft = node;
return bottomRight;
}
else
{
return node;
}
}