题目描述:
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
代码思路:
/*** 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) {if(preorder.length==0){return null;}// 初始化哈希表,存储中序遍历的每个节点值和索引HashMap<Integer, Integer> inorderMap = new HashMap<>();for (int i = 0; i < inorder.length; i++) {inorderMap.put(inorder[i], i);}TreeNode root = build(0,preorder.length-1,0,preorder,inorderMap);return root;}public TreeNode build(int low,int high,int preindex,int[] preorder, HashMap<Integer, Integer> inorderMap){if(low>high){return null;}// 获取当前节点的值int val = preorder[preindex];TreeNode node = new TreeNode(val); // 获取当前节点在inorder中的索引int index = inorderMap.get(node.val);// 递归构建左子树和右子树,并传递更新后的preindexnode.left = build(low,index-1,preindex+1,preorder,inorderMap);node.right = build(index+1,high,preindex+(index-low)+1,preorder,inorderMap);return node;}
}
注意:preindex的值!!!
时间和空间复杂度:
- 时间复杂度:
O(n)
。哈希表的构建和每个递归调用的操作都是O(1)
,所以总体时间复杂度是O(n)
,其中n
是节点数。 - 空间复杂度:
O(n)
,空间用于存储哈希表和递归调用栈。
改进一下,preindex的值 设置为全局变量
class Solution {private int preindex; public TreeNode buildTree(int[] preorder, int[] inorder) {if(preorder.length==0){return null;}// 初始化哈希表,存储中序遍历的每个节点值和索引HashMap<Integer, Integer> inorderMap = new HashMap<>();for (int i = 0; i < inorder.length; i++) {inorderMap.put(inorder[i], i);}TreeNode root = build(0,preorder.length-1,preindex,preorder,inorderMap);return root;}public TreeNode build(int low,int high,int preindex,int[] preorder, HashMap<Integer, Integer> inorderMap){if(low>high){return null;}// 获取当前节点的值int val = preorder[preindex];TreeNode node = new TreeNode(val); // 获取当前节点在inorder中的索引int index = inorderMap.get(node.val);// 递归构建左子树和右子树,并传递更新后的preindexnode.left = build(low,index-1,preindex+1,preorder,inorderMap);node.right = build(index+1,high,preindex+(index-low)+1,preorder,inorderMap);return node;}
}