1138. Postorder Traversal (25)

简介: #include #include #include using namespace std;int n;vector pre, in, post;struct node{ int data; nod...
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<int> pre, in, post;
struct node{
  int data; 
  node *l, *r;
};
node *build(int preL, int preR, int inL, int inR){
  if(preL > preR) return NULL;
  node *root = new node;
  root->data = pre[preL];
  int k;
  for(k = inL; k <= inR; k++)
    if(in[k] == pre[preL]) break;
  int leftnum = k - inL;
  root->l = build(preL + 1, preL + leftnum, inL, k - 1);
  root->r = build(preL + leftnum + 1, preR, k + 1, inR);
  return root;
}
void postorder(node *root){
  if(root == NULL) return;
  postorder(root->l);
  postorder(root->r);
  post.push_back(root->data);
}


int main()
{
  cin >> n;
  pre.resize(n);
  in.resize(n);
  for(int i = 0; i < n; i++) cin >> pre[i];
  for(int i = 0; i < n; i++) cin >> in[i];
  node *root = build(0, n-1, 0, n-1);
  postorder(root);
  cout << post[0] << endl;
  return 0;
}

目录
相关文章
LeetCode 145. Binary Tree Postorder Traversal
给定一个二叉树,返回它的后序遍历。
71 0
LeetCode 145. Binary Tree Postorder Traversal
【1138】Postorder Traversal (25 分)
【1138】Postorder Traversal (25 分) 【1138】Postorder Traversal (25 分)
85 0
|
算法 Java Python
LeetCode 94:二叉树的中序遍历 Binary Tree Inorder Traversal
题目: 给定一个二叉树,返回它的中序 遍历。 Given a binary tree, return the inorder traversal of its nodes' values. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出:...
974 0
[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/难度:Medium题目:106.
1137 0