C++ method of binary tree reconstruction based on first order and middle order traversal results

  • 2020-05-19 05:14:37
  • OfStack

The example of this paper describes the method of C++ to reconstruct a two-fork tree based on the results of the first and middle order traversal. I will share it with you for your reference as follows:

Topic:

Enter the results of the preorder traversal and the middle order traversal of a two-tree to reconstruct the two-tree. Assume that the input preorder traversal and the middle order traversal results do not contain repeating Numbers. For example, if the preorder traversal sequence {1,2,4,7,3,5,6,8} and the middle order traversal sequence {4,7,2,1,5,3,8,6} are entered, the 2 fork tree is rebuilt and returned.

Implementation code:


#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) {}
};
// create 2 Tree algorithm 
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]); // The first 1 A is the root node 
  int rootPos = 0; // The position of the root node in the middle order traversal 
  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;
}
// Print the subsequent traversal order 
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 << " The first order traversal sequence is  1 2 4 5 3 6" << endl;
  cout << " The middle order traversal sequence is  4 2 5 1 6 3" << endl;
  TreeNode* root = reConstructBinaryTree(preVec, midVec);
  cout << " The subsequent traversal sequence is  ";
  printNodeValue(root);
  cout << endl;
  system("pause");
}
/*
 test 2 Fork tree shape: 
      1
  2       3 
 4  5    6
*/

Operation results:


 The first order traversal sequence is  1 2 4 5 3 6
 The middle order traversal sequence is  4 2 5 1 6 3
 The subsequent traversal sequence is  4 5 2 6 3 1
 Please press any key to continue . . .

I hope this article is helpful to you C++ programming.


Related articles: