关闭

Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal

99人阅读 评论(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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12081次
    • 积分:1926
    • 等级:
    • 排名:千里之外
    • 原创:183篇
    • 转载:34篇
    • 译文:0篇
    • 评论:0条
    文章分类