Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

164人阅读 评论(0)

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// preorder determines the root of a tree, inorder determines the left and right child of a tree
public static TreeNode buildTreePreIn(int[] preorder, int ps, int pe, int[] inorder, int is, int ie, HashMap<Integer, Integer> iMap) {

if (ps > pe) return null;

// the first element of a pre-order is the root
TreeNode root = new TreeNode(preorder[ps]);
if (ps == pe) return root;

int index = iMap.get(preorder[ps]);
root.left = buildTreePreIn(preorder, ps+1, index-is+ps, inorder, is, index-1, iMap);
root.right = buildTreePreIn(preorder, index-is+ps+1, pe, inorder, index+1, ie, iMap);
return root;
}

public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer, Integer> iMap = new HashMap<Integer, Integer>();
for (int i=0; i<inorder.length; i++)
iMap.put(inorder[i], i);
return buildTreePreIn(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1, iMap);
}
}

0
0

个人资料
• 访问：19046次
• 积分：1963
• 等级：
• 排名：千里之外
• 原创：183篇
• 转载：34篇
• 译文：0篇
• 评论：0条
文章分类