• [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 };
  • 相关阅读:
    "Key Violation" with ClientDataSet
    c# 的关键字 params,out,ref
    eval && JSON.parse
    json2.js
    C#中的索引器
    call , apply , caller , callee
    iphone&ipad图标去除高亮的光圈效果
    调用系统路线导航
    调科大讯飞出现的问题
    得到汉字首字母在表中的顺序位置
  • 原文地址:https://www.cnblogs.com/skycore/p/5038227.html
Copyright © 2020-2023  润新知