[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

题目描述:(链接)

Given preorder and inorder 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>& preorder, vector<int>& inorder) {
13         return buildTree(begin(preorder), end(preorder), begin(inorder), end(inorder));
14     }
15     
16 private:
17     TreeNode *buildTree(vector<int>::iterator p_first, vector<int>::iterator p_last, 
18                         vector<int>::iterator i_first, vector<int>::iterator i_last) {
19         if (p_first == p_last) return nullptr;
20         if (i_first == i_last) return nullptr;
21         
22         auto root = new TreeNode(*p_first);
23         auto inRootPos = find(i_first, i_last, *p_first);
24         auto leftSize = distance(i_first, inRootPos);
25         
26         root->left = buildTree(next(p_first), next(p_first, leftSize + 1), i_first, next(i_first, leftSize));
27         root->right = buildTree(next(p_first, leftSize + 1), p_last, next(inRootPos), i_last);
28         
29         return root;
30     }
31 };

 

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