C++基于先序、中序遍歷結(jié)果重建二叉樹的方法
本文實(shí)例講述了C++基于先序、中序遍歷結(jié)果重建二叉樹的方法。分享給大家供大家參考,具體如下:
題目:
輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請(qǐng)重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復(fù)的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。
實(shí)現(xiàn)代碼:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//創(chuàng)建二叉樹算法
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> mid)
{
int nodeSize = mid.size();
if (nodeSize == 0)
return NULL;
vector<int> leftPre, leftMid, rightPre, rightMid;
TreeNode* phead = new TreeNode(pre[0]); //第一個(gè)當(dāng)是根節(jié)點(diǎn)
int rootPos = 0; //根節(jié)點(diǎn)在中序遍歷中的位置
for (int i = 0; i < nodeSize; i++)
{
if (mid[i] == pre[0])
{
rootPos = i;
break;
}
}
for (int i = 0; i < nodeSize; i++)
{
if (i < rootPos)
{
leftMid.push_back(mid[i]);
leftPre.push_back(pre[i + 1]);
}
else if (i > rootPos)
{
rightMid.push_back(mid[i]);
rightPre.push_back(pre[i]);
}
}
phead->left = reConstructBinaryTree(leftPre, leftMid);
phead->right = reConstructBinaryTree(rightPre, rightMid);
return phead;
}
//打印后續(xù)遍歷順序
void printNodeValue(TreeNode* root)
{
if (!root){
return;
}
printNodeValue(root->left);
printNodeValue(root->right);
cout << root->val<< " ";
}
int main()
{
vector<int> preVec{ 1, 2, 4, 5, 3, 6 };
vector<int> midVec{ 4, 2, 5, 1, 6, 3 };
cout << "先序遍歷序列為 1 2 4 5 3 6" << endl;
cout << "中序遍歷序列為 4 2 5 1 6 3" << endl;
TreeNode* root = reConstructBinaryTree(preVec, midVec);
cout << "后續(xù)遍歷序列為 ";
printNodeValue(root);
cout << endl;
system("pause");
}
/*
測(cè)試二叉樹形狀:
1
2 3
4 5 6
*/
運(yùn)行結(jié)果:
先序遍歷序列為 1 2 4 5 3 6 中序遍歷序列為 4 2 5 1 6 3 后續(xù)遍歷序列為 4 5 2 6 3 1 請(qǐng)按任意鍵繼續(xù). . .
希望本文所述對(duì)大家C++程序設(shè)計(jì)有所幫助。
相關(guān)文章
C++中sln,vcxproj,vcxproj.filters,lib,dll,exe的含義說明
這篇文章主要介紹了C++中sln,vcxproj,vcxproj.filters,lib,dll,exe的含義說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
C++中strlen(),sizeof()與size()的區(qū)別
本文主要介紹了C++中strlen(),sizeof()與size()的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05

