首页 > 代码库 > [LeetCode]105 Construct Binary Tree from Preorder and Inorder Traversal
[LeetCode]105 Construct Binary Tree from Preorder and Inorder Traversal
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。