Question
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Solution
参考:http://www.cnblogs.com/zhonghuasong/p/7096150.html
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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0 || inorder.size() == 0)
return NULL;
return ConstructTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* ConstructTree(vector<int>& preorder, vector<int>& inorder,
int pre_start, int pre_end, int in_start, int in_end) {
int rootValue = preorder[pre_start];
TreeNode* root = new TreeNode(rootValue);
if (pre_start == pre_end) {
if (in_start == in_end)
return root;
}
int rootIn = in_start;
while (rootIn <= in_end && inorder[rootIn] != rootValue)
rootIn++;
int preLeftLength = rootIn - in_start;
if (preLeftLength > 0) {
root->left = ConstructTree(preorder, inorder, pre_start + 1, preLeftLength, in_start, rootIn - 1);
}
// 左子树的对大长度就是in_end - in_start
if (preLeftLength < in_end - in_start) {
root->right = ConstructTree(preorder, inorder, pre_start + 1 + preLeftLength, pre_end, rootIn + 1, in_end);
}
return root;
}
};