来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ 9 20
/ 15 7
二叉树结构
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){ val = x; }
}
前序遍历特点:节点按照 [根节点|左子树|右子树] 排序
中序遍历特点:节点按照 [左子树|根节点|右子树] 排序
根据以上特点,可得重构二叉树的步骤:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer,Integer> dic = new HashMap<>();//存放中序遍历 <值,索引> 键值对,便于查询根节点值的索引
for(int i = 0; i < inorder.length; i++)
dic.put(inorder[i],i);
return build(preorder,0,0,inorder.length-1,dic);
}
public TreeNode build(int[] preorder,int pre_root,int in_left,int in_right,HashMap<Integer,Integer> dic){
if(in_left>in_right) return null;
TreeNode root = new TreeNode(preorder[pre_root]);
int i = dic.get(root.val);//获取根节点在 中序遍历 中的索引
root.left = build(preorder,pre_root+1,in_left,i-1,dic);//获取左子节点
root.right = build(preorder,pre_root+i-in_left+1,i+1,in_right,dic);//获取又子节点
return root;
}
}
执行用时:2ms
内存消耗:40.1MB
原文:https://www.cnblogs.com/HenuAJY/p/13164317.html