标签:leetcode
https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
http://blog.csdn.net/linhuanmars/article/details/24389549
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { int len = preorder.length; Map<Integer, Integer> inmap = new HashMap<>(); for (int i = 0 ; i < len ; i ++) { inmap.put(inorder[i], i); } return help(preorder, 0, len - 1, inmap, 0, len - 1); } private TreeNode help(int[] preorder, int ps, int pe, Map<Integer, Integer> inmap, int is, int ie) { if (ps > pe || is > ie) return null; // Root is preorder[ps]; TreeNode root = new TreeNode(preorder[ps]); int inpos = inmap.get(root.val); int leftnodes = inpos - is; // How many nodes on the left of root. root.left = help(preorder, ps + 1, ps + leftnodes, inmap, is, inpos - 1); root.right = help(preorder, ps + leftnodes + 1, pe, inmap, inpos + 1, ie); return root; } }
[LeetCode]105 Construct Binary Tree from Preorder and Inorder Traversal
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1599616