106. Construct Binary Tree from Inorder and Postorder Traversal

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了106. Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。

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

Note:
You may assume that duplicates do not exist in the tree.

========

利用:中序+后序遍历

====

code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    ///
    template<typename Iterator>
    TreeNode *help_buildTree_ip(Iterator in_first,Iterator in_last,
        Iterator post_first,Iterator post_last){
        if(in_first == in_last) return nullptr;
        if(post_first == post_last) return nullptr;

        auto val = *prev(post_last);
        TreeNode *root = new TreeNode(val);

        auto in_root_pos = find(in_first,in_last,val);
        auto left_size = distance(in_first,in_root_pos);
        auto post_left_last = next(post_first,left_size);

        root->left = help_buildTree_ip(in_first,in_root_pos,post_first,post_left_last);
        root->right = help_buildTree_ip(next(in_root_pos),in_last,post_left_last,prev(post_last));

        return root;
    }
    TreeNode* buildTree_ip(vector<int> &inorder,vector<int> &postorder){
        return help_buildTree_ip(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
    }
};

 

以上是关于106. Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal

[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal