105. Construct Binary Tree from Preorder and Inorder Traversal
by Botao Xiao
Question:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
Thinking:
- Method:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0) return null;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < inorder.length; i++)
map.put(inorder[i], i);
return createTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
}
public static TreeNode createTree(int[] preorder, int pStart, int pEnd, int[] inorder, int iStart, int iEnd, Map<Integer, Integer> map){
if(pStart > pEnd || iStart > iEnd) return null;
int rootVal = preorder[pStart];
TreeNode root = new TreeNode(rootVal);
int rootIndex = map.get(rootVal);
int len = rootIndex - iStart;
root.left = createTree(preorder, pStart + 1, pStart + len, inorder, iStart, rootIndex - 1, map);
root.right = createTree(preorder, pStart + len + 1, pEnd, inorder, rootIndex + 1, iEnd, map);
return root;
}
}
二刷
- 二刷的时候大概记得方法,但是还是参考了一刷时候的代码。一刷的时候其实也不是自己想出来的,而且还重复写了好几次。
- 根据前序遍历的结果定位出在后序遍历中头结点的位置,通过计算计算可以得到左树和右树的长度,通过递归操作可以不断创建出左右结点。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null) return null; Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < inorder.length; i++) map.put(inorder[i], i); return createTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map); } private TreeNode createTree(int[] preorder, int pStart, int pEnd, int[] inorder, int iStart, int iEnd, Map<Integer, Integer> map){ if(pStart > pEnd || iStart > iEnd) return null; TreeNode node = new TreeNode(preorder[pStart]); int index = map.get(preorder[pStart]); int len = index - iStart; node.left = createTree(preorder, pStart + 1, pStart + len, inorder, iStart, index - 1, map); node.right = createTree(preorder, pStart + len + 1, pEnd, inorder, index + 1, iEnd, map); return node; } }
Subscribe via RSS