zoukankan      html  css  js  c++  java
  • [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal

    题目描述:(链接)

    Given inorder and postorder traversal of a tree, construct the binary tree.

    解题思路:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    13         return buildTree(begin(inorder), end(inorder), begin(postorder), end(postorder));
    14     }
    15 private:
    16     TreeNode *buildTree(vector<int>::iterator in_first, vector<int>::iterator in_last, 
    17                         vector<int>::iterator post_first, vector<int>::iterator post_last) {
    18         if (in_first == in_last) return nullptr;
    19         if (post_first == post_last) return nullptr;
    20         
    21         auto val = *prev(post_last);
    22         TreeNode *root = new TreeNode(val);
    23         auto in_root_pos = find(in_first, in_last, val);
    24         auto in_left_size = distance(in_first, in_root_pos);
    25         auto post_left_last = next(post_first, in_left_size);
    26         
    27         root->left = buildTree(in_first, in_root_pos, post_first, post_left_last);
    28         root->right = buildTree(next(in_root_pos), in_last, post_left_last, prev(post_last));
    29         
    30     }
    31 };
  • 相关阅读:
    atcoder #082 E 暴力 计算几何
    LightOJ 1364 树形DP
    gym100712 ACM Amman Collegiate Programming Contest
    CF757 C hash
    CF844 C 置换 水
    CF544 C 背包 DP
    CF540 D 概率 DP
    CF540 C BFS 水
    CF540 B 贪心
    CF745 C 并查集
  • 原文地址:https://www.cnblogs.com/skycore/p/5038227.html
Copyright © 2011-2022 走看看