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 };
  • 相关阅读:
    C++树状数组详解
    状态码
    java面试教程视频
    学生管理系统学生基本信息查询(1)
    学生管理系统导包
    学生信息管理系统数据库设计
    SSH简单项目
    MyBatis入门
    Struts配置详解
    Struts的使用
  • 原文地址:https://www.cnblogs.com/skycore/p/5038227.html
Copyright © 2011-2022 走看看