从中序与后序遍历序列构造二叉树

leetCode刷题:从中序与后序遍历序列构造二叉树

题目介绍

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:在这里插入图片描述

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

解题思路

通过后序遍历来确定根节点,然后通过根节点在中序遍历序列中的位置来将中序遍历序列划分为左右子树。

递归调用,直到不能再划分(left > right)

代码实现

#include <limits.h>

#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
  int post_index;
  map<int, int> index_map;

 public:
  TreeNode* helper(int in_left, int in_right, vector<int>& inorder,
                   vector<int>& postorder) {
    if (in_left > in_right) return nullptr;
    int root_val = postorder[post_index];
    int index = index_map[root_val];
    post_index--;
    TreeNode* root = new TreeNode(root_val);
    root->right = helper(index + 1, in_right, inorder, postorder);
    root->left = helper(in_left, index - 1, inorder, postorder);
    return root;
  }
  TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    post_index = (int)postorder.size() - 1;
    for (int i = 0; i < inorder.size(); i++) index_map[inorder[i]] = i;
    return helper(0, post_index, inorder, postorder);
  }
  void preTraversal(TreeNode* root) {
    if (!root) {
      return;
    }
    cout << root->val << " ";
    preTraversal(root->left);
    preTraversal(root->right);
    return;
  }
  void inorderTraversal(TreeNode* root) {
    if (!root) {
      return;
    }
    inorderTraversal(root->left);
    cout << root->val << " ";
    inorderTraversal(root->right);
    return;
  }
};
int main() {
  Solution a;
  vector<int> test1{9, 3, 15, 20, 7};
  vector<int> test2{9, 15, 7, 20, 3};
  TreeNode* T = a.buildTree(test1, test2);
  a.preTraversal(T);
  cout << endl;
  a.inorderTraversal(T);
  cout << endl;
  return 0;
}

运行截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值