发现写个代码不容易,虽然很明白怎么回事,但是道和术是不同的,术需要懂得代码实现的细节,下面的代码,好几个地方一开始写错,死活运行不了,现在行了。。有问题请不吝赐教!
/*
* BSTree2BILinkList.cpp
*
* Created on: 2013-4-2
* Author: CJ
*/
#include<iostream>
using namespace std;
struct BSTreeNode{
int m_nValue;
BSTreeNode *m_pLeft;
BSTreeNode *m_pRight;
};
// @param root The root node of the tree
// @return The head node of the converted list
void helper(BSTreeNode *& head, BSTreeNode *& tail, BSTreeNode *root){
BSTreeNode *lt, *rh;
//if root is NULL
if(root == NULL){
head = NULL;
tail = NULL;
return;
}
//recursion
helper(head, lt, root->m_pLeft);
helper(rh, tail, root->m_pRight);
//if root is not NULL
if(lt != NULL){
lt->m_pRight = root;
root->m_pLeft = lt;
}else {
head = root;
}
if(rh != NULL){
rh->m_pLeft = root;
root->m_pRight = rh;
}else {
tail = root;
}
}
BSTreeNode* treeToLinkedList(BSTreeNode* root)
{
BSTreeNode *head, *tail;
helper(head,tail,root);
return head;
}
int main()
{
/* A
* / \
* B C
* / \/ \
* D EF G
*
* 转成双向链表
* D=B=E=A=F=C=G
*/
BSTreeNode A; A.m_nValue = 4;
BSTreeNode B; B.m_nValue = 2;
BSTreeNode C; C.m_nValue = 6;
BSTreeNode D; D.m_nValue = 1;
BSTreeNode E; E.m_nValue = 3;
BSTreeNode F; F.m_nValue = 5;
BSTreeNode G; G.m_nValue = 7;
D.m_pLeft = NULL;D.m_pRight = NULL;
E.m_pLeft = NULL;E.m_pRight = NULL;
F.m_pLeft = NULL;F.m_pRight = NULL;
G.m_pLeft = NULL;G.m_pRight = NULL;
B.m_pLeft = &D;
B.m_pRight = &E;
C.m_pLeft = &F;
C.m_pRight = &G;
A.m_pLeft = &B;
A.m_pRight = &C;
BSTreeNode *LinkedList = treeToLinkedList(&A);
while(LinkedList != NULL){
cout<<LinkedList->m_nValue<<endl;
LinkedList = LinkedList->m_pRight;
}
return 0;
}