105. 从前序与中序遍历序列构造二叉树:
题目链接 :105. 从前序与中序遍历序列构造二叉树
题目:
给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
思路:
1、递归函数:
-
根据前序和中序遍历规律,首先找到根节点,从而判断左右子树的边界
-
在数组对应左右子树的范围内递归不断寻找根节点
-
为了减少每次寻找根节点的时空开销,将节点放入HashMap,需要其作为根节点出现时get
AC代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<inorder.length;i++)
{
map.put(inorder[i],i);
}
int n=preorder.length;
return build(preorder,0,n,inorder,0,n,map);
}
public TreeNode build(int[] preorder,int ps,int pe,int[] inorder,int is,int ie,HashMap<Integer,Integer> map)
{
if(ps==pe)
{
return null;
}
int rootv=preorder[ps];
TreeNode root=new TreeNode(rootv);
int irootIdx=map.get(rootv);
int ln=irootIdx-is;
root.left=build(preorder,ps+1,ps+ln+1,inorder,is,irootIdx,map);
root.right=build(preorder,ps+ln+1,pe,inorder,irootIdx+1,ie,map);
return root;
}
}