问题描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
解题思路:
按照前序遍历的序列构建二叉树,左右子树可以根据中序遍历判断。
代码实现:
import java.util.HashMap;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
//利用原理,先序遍历的第一个节点就是根。在中序遍历中通过根 区分哪些是左子树的,哪些是右子树的
public class text01 {
static HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();//标记中序遍历
static int[] pre;//保留的先序遍历
public static void main(String[] args) {
int[] pr = {3,9,20,15,7};
int[] in = {9,3,15,20,7};
System.out.println(buildTree(pr, in));
}
public static TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode tree = null;
pre = preorder;
for(int i=0; i<preorder.length; i++){
map.put(inorder[i], i);
}
tree = recursive(0, 0, preorder.length-1);
return tree;
}
/**
* @param pre_root_idx 先序遍历的索引
* @param left 中序遍历的索引(子树的左边界)
* @param right 中序遍历的索引(子树的右边界)
*/
public static TreeNode recursive(int pre_root_idx, int left, int right) {
if(left > right){
return null;
}
TreeNode root = new TreeNode(pre[pre_root_idx]);
int idx = map.get(pre[pre_root_idx]); //在中序遍历中对应的位置
root.left = recursive(pre_root_idx+1, left, idx-1);
root.right = recursive(pre_root_idx+(idx-left)+1 , idx+1, right);
return root;
}
}
提交结果: