目录
思路分析
首先需要注意: 本题是没有重复值的!
优化: 利用哈希表,快速找到中序值对应的下标值
cpp
/**
* 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:
unordered_map<int,int> d; // 优化: 记录中序序列的位置
vector<int> preorder,inorder; // 为了dfs方便,两个序列定义为全局
// 先序的序列范围 和 中序的序列范围 (闭区间)
TreeNode* dfs(int pl,int pr,int il,int ir){
if(pl>pr)return NULL;
auto root = new TreeNode(preorder[pl]); // 根节点的值
int k = d[root->val];
auto left = dfs(pl+1,pl+k-il,il,k-1);
auto right = dfs(pl+k-il+1,pr,k+1,ir);
root->left = left,root->right=right;
return root;
}
TreeNode* buildTree(vector<int>& _preorder, vector<int>& _inorder) {
preorder = _preorder,inorder=_inorder;
for(int i=0;i<inorder.size();i++)d[inorder[i]]=i;
return dfs(0,preorder.size()-1,0,inorder.size()-1);
}
};
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
d = dict()
def dfs(pl,pr,il,ir):
if pl>pr:return None
root = TreeNode(preorder[pl])
k = d[root.val]
left = dfs(pl+1,pl+k-il,il,k-1)
right = dfs(pl+k-il+1,pr,k+1,ir)
root.left,root.right=left,right
return root
for i,x in enumerate(inorder):
d[x]=i
return dfs(0,len(preorder)-1,0,len(inorder)-1)