[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 };

 

posted @ 2015-12-11 10:30  skycore  阅读(135)  评论(0编辑  收藏  举报