此题目是冲一篇博客上面看到的http://blog.csdn.net/v_JULY_v/article/details/6057286,最后我下载了他的解答,发现有错误,准备直接看他解答的博客,结果没有发现,所以自己就在他的思想上,进行了,重新编写
题目是这样的,
一下是我的源代码
数据没有完全一样,在创建二叉树的时候,没有优化,懂那个意识就可了我觉得
#include <iostream>
struct BSTreeNode{
int m_Value;
BSTreeNode * m_pLeft;
BSTreeNode * m_pRight;
};
BSTreeNode *head,*tail;
void InitTree(BSTreeNode * root){
BSTreeNode *tmp1 = new BSTreeNode;
tmp1->m_Value = 6;
tmp1->m_pLeft = NULL;
tmp1->m_pRight = NULL;
root->m_Value =10;
root->m_pLeft = tmp1;
BSTreeNode *tmp2 = new BSTreeNode;
tmp2->m_Value = 14;
tmp2->m_pLeft = NULL;
tmp2->m_pRight = NULL;
root->m_pRight = tmp2;
BSTreeNode *tmp3 = new BSTreeNode;
tmp3->m_pLeft = NULL;
tmp3->m_pRight = NULL;
tmp3->m_Value = 4;
BSTreeNode *tmp4 = new BSTreeNode;
tmp4->m_pLeft = NULL;
tmp4->m_pRight = NULL;
tmp4->m_Value = 8;
tmp1->m_pLeft =tmp3;
tmp1->m_pRight = tmp4;
BSTreeNode *tmp5 = new BSTreeNode;
tmp5->m_pLeft = NULL;
tmp5->m_pRight = NULL;
tmp5->m_Value = 12;
tmp4->m_pLeft = tmp5;
return;
}
void Trival( BSTreeNode * root )
{
if (head == NULL)
{
head = root;
tail = root;
}
else{
tail->m_pRight = root;
root->m_pLeft = tail;
tail = root;
}
return;
}
void helper ( BSTreeNode *root){
if (root == NULL)
return;
helper( root->m_pLeft);
Trival( root);
helper( root->m_pRight);
return ;
}
BSTreeNode * treeToLinkedList(BSTreeNode * root){
helper(root);
return head;
}
int main(int argc, _TCHAR* argv[])
{
BSTreeNode *root = new BSTreeNode;
InitTree(root);
treeToLinkedList(root);
for (int i =0; i<6; ++i )
{
//顺时针测试
/*std::cout<<head->m_Value<<std::endl;
head = head->m_pRight;*/
//逆时针测试
std::cout<<tail->m_Value<<std::endl;
tail = tail->m_pLeft;
}
return 0;
}
整个转换过程,其实就是一个二叉树的中序遍历,如果大家有个更好的方式,可以探讨,由于没有写过几次博客,所以就这个样子