输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
分析:
- 前序遍历数组的第一个元素一定是根节点
- 然后看中序遍历的数组,从根节点元素分开,各自是左右子树
- 然后数组下标做处理可以得到左右子树的长度(在数组中)
- 然后就得到了左子树前、中序遍历数组
- 得到了右子树前、中序遍历数组
- 。。。。。。。
- 重复重复分割分割
- 合并合并
- 完成
大概就是这样想的
灵魂画手上线
public class Solution {
Map<Integer, Integer> map;
int[] preorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
int preLen = preorder.length;
int inLen = inorder.length;
if (preLen != inLen) {
return null;
}
this.preorder =preorder;
map =new HashMap<Integer, Integer>(inLen);
for (int i = 0; i < inLen; i++) {
map.put(inorder[i], i);
}
return rec(0, preLen - 1, 0, inLen - 1);
}
private TreeNode rec(int preL, int preR, int inL, int inR) {
if (preL>preR||inL>inR) {
return null;
}
int pivot=preorder[preL];
int pivotIndex=map.get(pivot);
TreeNode root = new TreeNode(pivot);
root.left=rec(preL+1, preL+pivotIndex-inL, inL, pivotIndex-1);
root.right=rec(preL+pivotIndex-inL+1, preR, pivotIndex+1, inR);
return root;
}
}
class TreeNode {
int val;
TreeNode right;
TreeNode left;
public TreeNode(int x) {
val = x;
}
}
最后许愿一个满意的offer
我太菜了!