C++基於先序、中序遍歷結果重建二叉樹的方法。本站提示廣大學習愛好者:(C++基於先序、中序遍歷結果重建二叉樹的方法)文章只能為提供參考,不一定能成為您想要的結果。以下是C++基於先序、中序遍歷結果重建二叉樹的方法正文
作者:難免有錯_
這篇文章主要介紹了C++基於先序、中序遍歷結果重建二叉樹的方法,結合實例形式分析了基於C++構建二叉樹的相關操作技巧,需要的朋友可以參考下本文實例講述了C++基於先序、中序遍歷結果重建二叉樹的方法。分享給大家供大家參考,具體如下:
題目:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
實現代碼:
#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) {}
};
//創建二叉樹算法
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]); //第一個當是根節點
int rootPos = 0; //根節點在中序遍歷中的位置
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;
}
//打印後續遍歷順序
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 << "後續遍歷序列為 ";
printNodeValue(root);
cout << endl;
system("pause");
}
/*
測試二叉樹形狀:
1
2 3
4 5 6
*/
運行結果:
先序遍歷序列為 1 2 4 5 3 6 中序遍歷序列為 4 2 5 1 6 3 後續遍歷序列為 4 5 2 6 3 1 請按任意鍵繼續. . .
希望本文所述對大家C++程序設計有所幫助。