105. Construct Binary Tree from Preorder and Inorder Traversal
题目描述:
Given preorder and inorder traversal of a tree, construct the binary tree.
Example 1:
null
Note: You may assume that duplicates do not exist in the tree.
题目翻译
给定一个树的前序和中序遍历,构造二叉树。
示例1:
null
注意: 你可以假设树中不存在重复项
解题方案
标签: Depth-first Search
思路:
- 依照题目提示,我们假设树中不存在重复项
- 那么我们可以通过前序遍历告诉我们根节点,在中序遍历上分开左子树和右子树
- 每一步都寻找根节点,分开左右子树,建立树就可以了
代码:
/**
* 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:
typedef vector<int>::iterator Iter;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return createTree(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
}
TreeNode* createTree(Iter preBegin,Iter preEnd,Iter inBegin,Iter inEnd){
if(inBegin == inEnd) return NULL;
TreeNode* root = new TreeNode(*preBegin);
Iter inRoot = find(inBegin,inEnd,*preBegin);
root->left = createTree(preBegin + 1 ,preBegin + 1 + (inRoot-inBegin),inBegin,inRoot);
root->right = createTree(preBegin + 1 + (inRoot-inBegin),preEnd,inRoot + 1,inEnd);
return root;
}
};
参考资料
- 作者:段静