輸入一棵二元查找樹,將該二元查找樹轉換成一個排序的雙向鏈表。
要求不能創建任何新的結點,只調整指針的指向。
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
};
#include<iostream>
#include<iomanip>
using namespace std;
//
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node, pre
BSTreeNode *m_pRight; // right child of node, next
};
BSTreeNode * Min(BSTreeNode *&tp)
{
if(NULL==tp->m_pLeft)
{
BSTreeNode * ret=tp;
if(NULL!=tp->m_pRight)
{
tp=tp->m_pRight;
}
else
{
tp=NULL;
}
return ret;
}
else
{
BSTreeNode * p2=tp; //fu
BSTreeNode * p1=p2->m_pLeft;//zi
while(p1->m_pLeft)
{
p2=p1;
p1=p1->m_pLeft;
}
p2->m_pLeft=p1->m_pRight;
return p1;
}
}
BSTreeNode *TreetoList(BSTreeNode *tp)
//返回生成的鏈表指針
{
if(!tp)
return NULL;
else
{
BSTreeNode *lp=Min(tp);
BSTreeNode *tem;
lp->m_pLeft=lp->m_pRight=NULL;
while(tp)
{
tem=Min(tp);
lp->m_pRight=tem;
tem->m_pLeft=lp;
lp=tem;
}
return lp;
}
}
int main()
{
system("pause");
return 0;
}
採用遞歸
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
BSTreeNode *ConvertNode(BSTreeNode * p_node , bool b)
{
if(!p_node) return NULL;
BSTreeNode * p_left=NULL;
BSTreeNode * p_right=NULL;
if(p_node->m_pLeft)
p_left=ConvertNode(p_node->m_pLeft,false);
if(p_left)
{
p_left->m_pRight=p_node;
p_node->m_pLeft=p_left;
}
if(p_node->m_pRight)
p_right=ConvertNode(p_node->m_pRight,true);
if(p_right)
{
p_node->m_pRight=p_right;
p_right->m_pLeft=p_node;
}
if(b)
{
while(p_node->m_pLeft)
p_node=p_node->m_pLeft;
}
else
{
while(p_node->m_pRight)
p_node=p_node->m_pRight;
}
return p_node;
}
BSTreeNode * Convert(BSTreeNode * t)
{
return ConvertNode(t,true);
}
int main()
{
system("pause");
return 0;
}