题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
知识点:
算法思路:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//1、建立根节点,前序遍历中第一个数字得到根节点值preorder[0]
//2、根据根节点来划分 前序数组 和 中序数组,找到 中序数组 中根节点的位置
//3、根据根节点的位置划分中序数组,中序数组根节点的左侧为左子树,右侧为右子树
//4、划分前序数组,根据中序数组的左右子树的大小
//5、递归处理左右子树
class Solution {
public:
TreeNode* buildTree(vector& preorder, vector& inorder) {
if(preorder.size()==0) return NULL;
else
{
int rootVal = preorder[0]; //根节点为前序遍历的第一个元素
TreeNode *root = new TreeNode(rootVal);
//查找中序遍历中根节点所在位置
vector::iterator pos = find(inorder.begin(),inorder.end(),rootVal);
vector inLeft(inorder.begin(),pos);
vector inRight(pos+1,inorder.end());
int inLeftSize = inLeft.size();
vector preLeft(preorder.begin()+1,preorder.begin()+inLeftSize+1);
vector preRight(preorder.begin()+inLeftSize+1,preorder.end());
root->left=buildTree(preLeft,inLeft);
root->right=buildTree(preRight,inRight);
return root;
}
}
};
//获取中序遍历中根节点的下标
int index=0;
for(;index preLeft;
preLeft.assign(preorder.begin()+1,preorder.begin()+1+index);
vector preRight;
preRight.assign(preorder.begin()+1+index,preorder.end());
vector inLeft;
inLeft.assign(inorder.begin(),inorder.begin()+index);
vector inRight;
inRight.assign(inorder.begin()+index+1,inorder.end());
class Solution {
public:
TreeNode* buildTree(vector& preorder, vector& inorder) {
if(preorder.size()==0 || inorder.size()==0) return NULL;
static int k=0;
int rootval = preorder[k++];
TreeNode *root = new TreeNode(rootval);
vector::iterator pos = find(inorder.begin(),inorder.end(),rootval);
if(pos != inorder.end())
{
vector inorderLeft = {inorder.begin(),pos};
vector inorderRight = {pos+1,inorder.end()};
root->left = buildTree(preorder,inorderLeft);
root->right = buildTree(preorder,inorderRight);
}
return root;
}
};