Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
由题意得,这题是给出一个二叉树的前序和中序序列,然后要求构造这样的一个二叉树。用递归的方法比较容易懂和好写,所以打算用递归写。例如给出一个前序序列是 1 2 4 5 3 6 7,中序序列为4 2 5 1 6 3 7。这个二叉树为:
观察两个序列,显然前序中的第一个就是根结点,观察中序,中序序列中的1是根节点,而前面部分是左子树,后面部分为右子树,所以递归的话,就可以这样划分成子问题来解决,代码如下:
Code(LeetCode运行16ms)
/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTree(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
}
TreeNode* buildTree(vector<int>::iterator pre_begin, vector<int>::iterator pre_end, vector<int>::iterator in_begin, vector<int>::iterator in_end) {
if (pre_begin == pre_end) {
return NULL;
}
if (in_begin == in_end) {
return NULL;
}
auto root = new TreeNode(*pre_begin);
auto RootPos = find(in_begin, in_end, *pre_begin);
auto leftSize = distance(in_begin, RootPos);
root -> left = buildTree(next(pre_begin), next(pre_begin, leftSize + 1), in_begin, next(in_begin, leftSize));
root -> right = buildTree(next(pre_begin, leftSize + 1), pre_end, next(RootPos), in_end);
return root;
}
};