[leetcode] Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
思路:类似上题,从preorder入手找到根节点然后在中序中分辨左右子树。
因为java不支持返回数组后面元素的地址,所以写起来不如C/C++优雅,需要传递一个范围或者要局部复制数组。
public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if (inorder.length == 0 || preorder.length == 0) return null; TreeNode res = build(preorder, 0, preorder.length, inorder, 0, inorder.length); return res; } private TreeNode build(int[] pre, int a, int b, int[] in, int c, int d) { if (b - a <= 0) return null; TreeNode root = new TreeNode(pre[a]); int idx = -1; for (int i = c; i < d; i++) { if (in[i] == pre[a]) idx = i; } // use the len, not idx int len = idx - c; root.left = build(pre, a + 1, a + 1 + len, in, c, c + len); root.right = build(pre, a + 1 + len, b, in, c + 1 + len, d); return root; } public static void main(String[] args) { new Solution().buildTree(new int[] { 3, 9, 20, 15, 7 }, new int[] { 9, 3, 15, 20, 7 }); } }
2022 回顾,如果每次都重新create 新数组递归下去,无法简单使用map来加快inorder里index的查找,因为index是global index。所以这里采用传递数组坐标的方式递归。
class Solution { private Map<Integer,Integer> inMap = new HashMap<>(); private int[] preorder; private int[] inorder; public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null){ return null; } this.preorder = preorder; this.inorder = inorder; for(int i=0;i<inorder.length;i++){ inMap.put(inorder[i],i); } return build(0, preorder.length, 0, inorder.length); } private TreeNode build(int preS, int preE, int inS, int inE){ if(preS==preE){ return null; } int rootVal = preorder[preS]; //be careful here, the idx is the global index here int idx = inMap.get(rootVal); int leftLen = idx - inS; TreeNode root = new TreeNode(rootVal); root.left = build(preS+1, preS+1+leftLen, inS, idx); root.right = build(preS+1+leftLen, preE, idx+1, inE); return root; } }