从前序与中序遍历序列构造二叉树
题目:从前序与中序遍历序列构造二叉树
给定一棵树的前序遍历 preorder
与中序遍历 inorder
。请构造二叉树并返回其根节点。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
题解
class Solution {
private int pre[];
private int middle[];
public TreeNode dfs(int pleft, int pright, int mleft, int mright) {
if (pright < pleft || mright < mleft) return null;
int val = pre[pleft];
int y = 0;
for (int i = mleft; i <= mright; i++) {
if (middle[i] == val) {
y = i;
break;
}
}
TreeNode root=new TreeNode(val);
root.left=dfs(pleft+1, pleft+y-mleft, mleft, y-1);
root.right=dfs(pleft+y-mleft+1, pright, y+1, mright);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
pre = preorder;
middle = inorder;
return dfs(0, preorder.length - 1, 0, inorder.length - 1);
}
}