Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:php开源博客系统源码 编辑:程序博客网 时间:2024/06/05 09:50
/** * 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
原创粉丝点击