举例:
思路:(1)通过先序遍历找到根节点的位置 3 再通过3在中序遍历中的位置找到3的左子树和右子树
(2) 在3的左子树中,找到左子树的根节点(9 在先序遍历中找到),然后重复步骤(1),即在中序遍历中找根节点9的左子树和右子树
(3)在3的右子树中,找到右子树的根节点(20 在先序遍历中 从3往右移左子树的长度就得到3的右子树根节点20),然后重复步骤(1)
代码如下:
unordered_map<int, int> inoderIdex;
class Solution {
//root 表示在前序遍历中的root的位置
// left 表示 前序遍历中root节点 在中序遍历中 对应的左子树边界
//right 表示 前序遍历中root节点 在中序遍历中 对应的右子树边界
TreeNode * dfs(vector<int>& preorder, vector<int>& inorder, int root, int left, int right)
{
if(left > right) return NULL;
int rootIdxInoder = inoderIdex[preorder[root]];
int leftTreeSize = rootIdxInoder - left;//左子树的长度
TreeNode * t = new TreeNode(preorder[root]);
t ->left = dfs(preorder, inorder, root + 1, left, rootIdxInoder-1 );
t ->right = dfs(preorder, inorder, root + leftTreeSize +1, rootIdxInoder+1, right);
return t;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(inorder.size() == 0) return NULL;
for(int i = 0; i < inorder.size(); i++)
{
inoderIdex[inorder[i]] = i;//将中序遍历的结果存储起来 便于找到左子树与右子树
}
return dfs(preorder, inorder, 0, 0 , inorder.size()-1);
}
};