原文链接:点击打开链接、
不申请新节点 将二叉树转换成双向链表
总结一下:在中序遍历中 进行转换
原题:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
分析:
首先是定义二元查找树,节点的数据结构如下:
struct BSTreeNode {
int m_nValue;
BSTreeNode* m_pLeft;
BSTreeNode* m_pRight;
};
再来分析题目要求, 不能创建任何新的节点 ,所以我们借助以下语句来实现节点之间的转换
typedef BSTreeNode DoubleList;
DoubleList * pHead;
DoubleList * pListIndex;
ps:这里是定义而不是创建!
之后就是定义三个功能函数了:
1.创建二元查找树的addBSTreeNode(BSTreeNode * & pCurrent,int value);
2.遍历二元查找树的void ergodicBSTree(BSTreeNode * pCurrent);
3.二叉树转换成list的
convertToDoubleList(BSTreeNode * pCurrent);
3.源码:
借用结构之法算法之道博主July写的源码
struct BSTreeNode {
int m_nValue;
BSTreeNode* m_pLeft;
BSTreeNode* m_pRight;
};
typedef BSTreeNode DoubleList;
DoubleList * pHead;
DoubleList * pListIndex;
void convertToDoubleList(BSTreeNode* pCurrent);
//创建二叉查找树
void addBSTreeNode(BSTreeNode * &pCurrent, int value)
//传的是pRoot的地址,所以对pCurrent的操作就是对pRoot的操作
{
if (pCurrent == NULL)
{
BSTreeNode* pBSTree = new BSTreeNode();
pBSTree->m_pLeft = NULL;
pBSTree->m_pRight = NULL;
pBSTree->m_nValue = value;
pCurrent = pBSTree;
}
else
{
if ((pCurrent->m_nValue) > value)
{
addBSTreeNode(pCurrent->m_pLeft, value);
}
else if((pCurrent->m_nValue) < value)
{
addBSTreeNode(pCurrent->m_pRight, value);
}
else
cout<<"重复加入节点"<<endl;
}
}
void ergodicBSTree(BSTreeNode* pCurrent)
{
if (pCurrent == NULL)
{
return;
}
if (pCurrent->m_pLeft != NULL)
{
ergodicBSTree(pCurrent->m_pLeft);
}
convertToDoubleList(pCurrent);
if (pCurrent->m_pRight != NULL)
{
ergodicBSTree(pCurrent->m_pRight);
}
}
void convertToDoubleList(BSTreeNode* pCurrent)
{
pCurrent->m_pLeft = pListIndex;
if (pListIndex != NULL)
{
pListIndex->m_pRight = pCurrent;
}
else
{
pHead = pCurrent;
}
pListIndex = pCurrent;
cout<<pCurrent->m_nValue<<endl;
}
ps:写的不错,July在算法上有非常深的功底,他的博文主页: http://my.csdn.net/v_july_v