雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當前位置:主頁 > 軟件編程 > C語言 >

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

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點擊:

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

題目:

輸入某二叉樹的前序遍歷和中序遍歷的結(jié)果,請重建出該二叉樹。假設(shè)輸入的前序遍歷和中序遍歷的結(jié)果中都不含重復的數(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
*/

運行結(jié)果:

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

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

上一篇:C語言在頭文件中定義const變量詳解

欄    目:C語言

下一篇:C語言指針應用簡單實例

本文標題:C++基于先序、中序遍歷結(jié)果重建二叉樹的方法

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1589.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有