根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路:找到中序遍历中根节点的位置index,将前序与中序分割成左右两部分,递归可求得左右子树
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int pSize = preorder.size();
int iSize = inorder.size();
if(pSize == 0 || iSize == 0 || pSize != iSize)
return NULL;
TreeNode* root = new TreeNode(preorder[0]); //根节点root
int index = 0;
while(preorder[0] != inorder[index]) //找到根节点在中序中的位置
index++;
vector<int> preLeft,preRight,inLeft,inRight;
for(int i=0;i<index;i++) //分割
{
preLeft.push_back(preorder[i+1]);
inLeft.push_back(inorder[i]);
}
for(int i=index+1;i<pSize;i++)
{
preRight.push_back(preorder[i]);
inRight.push_back(inorder[i]);
}
root->left = buildTree(preLeft,inLeft); //递归
root->right = buildTree(preRight,inRight);
return root;
}
};