二叉树的遍历
今天种树的主要任务是二叉树的遍历,知识点很简单,就是根据前序中序推后序的那个实现起来,细节有点绕。。
二叉树的遍历方式
随便找了一篇,规则很简单
https://blog.csdn.net/soundwave_/article/details/53120766
C++实现
题目要求是,根据前序和中序的结果推导树的结构,因为没输出不太好判断对错,所以我又把树后序遍历打印出来了。第一次是用数组实现的:
#include <iostream>
#include <stack>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pList;
BinaryTreeNode* m_pRight;
};
int preOrder[] = {1, 2, 4, 7, 3, 5, 6, 8};
int inOrder[] = {4, 7, 2, 1, 5, 3, 8, 6};
BinaryTreeNode* RecoverTree(int lp, int rp, int li, int ri)
{
int rootValue = preOrder[lp];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pList = nullptr;
root->m_pRight = nullptr;
if(lp == rp)
return root;
int lLeng;
for(int i = li; i <= ri; i++)
{
if(inOrder[i] == rootValue)
{
lLeng = i - li;
break;
}
}
if(lLeng > 0)
root->m_pList = RecoverTree(lp + 1, lp + lLeng, li, li + lLeng - 1);
if(ri > li + lLeng)
root->m_pRight = RecoverTree(lp + lLeng + 1, rp, li + lLeng + 1, ri);
return root;
}
//后序遍历
void BeOrder(BinaryTreeNode* tree)
{
if(tree->m_pList != nullptr)
BeOrder(tree->m_pList);
if(tree->m_pRight!= nullptr)
BeOrder(tree->m_pRight);
cout<< tree->m_nValue;
}
int main()
{
int leng = sizeof(preOrder)/sizeof(preOrder[0]);
BinaryTreeNode* tree = RecoverTree(0, leng-1, 0 ,leng-1);
BeOrder(tree);
return 0;
}
第二个是用指针,大体上差不多,就是熟悉一下指针
#include <iostream>
#include <stack>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pList;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* RecoverTree(int* lp, int* rp, int* li, int* ri)
{
int rootValue = lp[0];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pList = nullptr;
root->m_pRight = nullptr;
if(lp == rp)
{
return root;
}
int* rooti = li;
while(rooti[0]!=rootValue && rooti<=ri)
rooti++;
int lLeng = rooti - li;
if(lLeng > 0)
root->m_pList = RecoverTree(lp + 1, lp + lLeng , li, li + lLeng - 1);
if(ri > li + lLeng)
root->m_pRight = RecoverTree(lp + lLeng + 1, rp, li + lLeng + 1, ri);
return root;
}
void BeOrder(BinaryTreeNode* tree)
{
if(tree->m_pList != nullptr)
BeOrder(tree->m_pList);
if(tree->m_pRight!= nullptr)
BeOrder(tree->m_pRight);
cout<< tree->m_nValue;
}
int main()
{
int preOrder[] = {1, 2, 4, 7, 3, 5, 6, 8};
int inOrder[] = {4, 7, 2, 1, 5, 3, 8, 6};
int leng = sizeof(preOrder)/sizeof(preOrder[0]);
BinaryTreeNode* tree = RecoverTree(preOrder, preOrder+leng-1, inOrder, inOrder+leng-1);
BeOrder(tree);
return 0;
}
运行结果
两次结果都是一样的
我要辞职!!种树+3