1天1道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(1)题目
来源:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Given preorder and inorder traversal of a tree,construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
(2)解题
题目大意:根据2叉树的前序和中序遍历,构造出该2叉树
剑指offer上的老题了,前序遍历的第1个节点为根节点,在中序遍历中找到该节点,其左侧为根节点的左子树,后边为根节点的右子树。顺次递归下去便可以重构出该2叉树。
如:123和213,前序遍历找出根节点为1,在中序遍历213中找出1,则2为左子树,3为右子树。
class Solution {
public:
typedef vector<int>::iterator vi;
TreeNode* buildTree(vector<int>& preorder,vector<int>& inorder) {
if(preorder.empty()||inorder.empty()) return (TreeNode*)NULL;
vi preStart = preorder.begin();
vi preEnd = preorder.end()-1;
vi inStart = inorder.begin();
vi inEnd = inorder.end()-1;
return constructTree(preStart,preEnd,inStart,inEnd);
}
TreeNode* constructTree(vi preStart,vi preEnd,vi inStart,vi inEnd)
{
if(preStart>preEnd||inStart>inEnd) return NULL;
TreeNode* root = new TreeNode(*preStart);
if(preStart==preEnd||inStart==inEnd) return root;
vi rootIn = inStart;
while(rootIn!=inEnd){
if(*rootIn==*preStart) break;
else ++rootIn;
}
root->left = constructTree(preStart+1,preStart+(rootIn-inStart),rootIn-1);
root->right = constructTree(preStart+(rootIn-inStart)+1,rootIn+1,inEnd);
return root;
}
};