国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++基于先序、中序遍歷結果重建二叉樹的方法

2020-01-26 14:09:55
字體:
來源:轉載
供稿:網友

本文實例講述了C++基于先序、中序遍歷結果重建二叉樹的方法。分享給大家供大家參考,具體如下:

題目:

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數(shù)字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。

實現(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]); //第一個當是根節(jié)點  int rootPos = 0; //根節(jié)點在中序遍歷中的位置  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");}/*測試二叉樹形狀:      1  2       3  4  5    6*/

運行結果:

先序遍歷序列為 1 2 4 5 3 6中序遍歷序列為 4 2 5 1 6 3后續(xù)遍歷序列為 4 5 2 6 3 1請按任意鍵繼續(xù). . .

希望本文所述對大家C++程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 滦平县| 亳州市| 瑞昌市| 乌兰浩特市| 哈巴河县| 盈江县| 万州区| 宁海县| 玉溪市| 保亭| 分宜县| 望江县| 宁陵县| 谷城县| 卢氏县| 云和县| 罗源县| 沧州市| 石屏县| 永寿县| 孝感市| 富平县| 玉屏| 盐亭县| 抚顺县| 南华县| 镇沅| 牙克石市| 江孜县| 景洪市| 洞口县| 安阳市| 大冶市| 普定县| 乐至县| 大余县| 德钦县| 德钦县| 天津市| 苏尼特左旗| 沂南县|