二叉树线索化递归版本的代码,核心在于引用,起到画龙点睛的作用。。。。面试时候没想出来。。。明天继续更新非递归版本的二叉树线索化。。。
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* CreateBinaryTreeNode(int value);
void PrintTreeNode(const BinaryTreeNode* pNode);
void PrintTree(const BinaryTreeNode* pRoot);
// 申请二叉树节点
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
return pNode;
}
// 打印二叉树Node内容
void PrintTreeNode(const BinaryTreeNode* pNode)
{
if(pNode != NULL)
{
printf("value of this node is: %d\n", pNode->m_nValue);
if(pNode->m_pLeft != NULL)
printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
else
printf("left child is NULL.\n");
if(pNode->m_pRight != NULL)
printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
else
printf("right child is NULL.\n");
}
else
{
printf("this node is NULL.\n");
}
printf("\n");
}
// 打印二叉树
void PrintTree(const BinaryTreeNode* pRoot)
{
PrintTreeNode(pRoot);
if(pRoot != NULL)
{
if(pRoot->m_pLeft != NULL)
PrintTree(pRoot->m_pLeft);
if(pRoot->m_pRight != NULL)
PrintTree(pRoot->m_pRight);
}
}
void serialize(const BinaryTreeNode* pRoot, vector<int> &output)
{
int value = -10000;
if (pRoot != NULL)
{
value = pRoot->m_nValue;
}
output.push_back(value);
if (pRoot == NULL)
{
return;
}
serialize(pRoot->m_pLeft, output);
serialize(pRoot->m_pRight, output);
}
BinaryTreeNode* unserialize(vector<int> &input, int& i)
{
int len = input.size();
if (i >= len )
{
return NULL;
}
int value = input[i++];
if (value == -10000)
{
return NULL;
}
BinaryTreeNode* root = CreateBinaryTreeNode(value);
root->m_pLeft = unserialize(input, i);
root->m_pRight = unserialize(input, i);
return root;
}
BinaryTreeNode* unserialize(vector<int> &input)
{
int i = 0;
return unserialize(input, i);
}
int main()
{
vector<int> input;
vector<int> output;
input.push_back(1);
input.push_back(2);
input.push_back(-10000);
int i = 0;
BinaryTreeNode* root = unserialize(input);
PrintTree(root);
serialize(root, output);
for(i = 0; i < output.size(); ++i)
{
cout << output[i] << " ";
}
cout<< endl;
i = 0;
root = unserialize(input);
PrintTree(root);
return 0;
}