标签:
Note:
You may assume that duplicates do not exist in the tree.
Subscribe to see which companies asked this question
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length == 0) return null; int rootValue = preorder[0]; TreeNode root = new TreeNode(rootValue); if(preorder.length == 1) return root; int inorderRootIndex = 0; for(int i = 0; i<inorder.length; ++i) { if(inorder[i] == rootValue) { inorderRootIndex = i; break; } } int[] preorderLeftBranch = Arrays.copyOfRange(preorder, 1, inorderRootIndex+1); int[] preorderRightBranch = Arrays.copyOfRange(preorder, inorderRootIndex+1, preorder.length); int[] inorderLeftBranch = Arrays.copyOfRange(inorder, 0, inorderRootIndex); int[] inorderRightBranch = Arrays.copyOfRange(inorder, inorderRootIndex+1, inorder.length); root.left = buildTree(preorderLeftBranch, inorderLeftBranch); root.right = buildTree(preorderRightBranch, inorderRightBranch); return root; } }
/** * 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) { Map<Integer, Integer> inMap = new HashMap<Integer, Integer>(); for(int i = 0; i < inorder.length; i++) { inMap.put(inorder[i], i); } TreeNode root = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inMap); return root; } public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> inMap) { if(preStart > preEnd || inStart > inEnd) return null; TreeNode root = new TreeNode(preorder[preStart]); int inRoot = inMap.get(root.val); int numsLeft = inRoot - inStart; root.left = buildTree(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot - 1, inMap); root.right = buildTree(preorder, preStart + numsLeft + 1, preEnd, inorder, inRoot + 1, inEnd, inMap); return root; } }
105. Construct Binary Tree from Preorder and Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5274420.html