题解 | #从前序和中序遍历构造二叉树#
从前序和中序遍历构造二叉树
http://www.nowcoder.com/practice/0ee054a8767c4a6c96ddab65e08688f4
善用Java的工具类
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param preorder int整型一维数组 * @param inorder int整型一维数组 * @return TreeNode类 */ public TreeNode buildTree (int[] preorder, int[] inorder) { // write code here if(preorder.length==0||inorder.length==0) return null; TreeNode root = new TreeNode(preorder[0]); int mid = 0; for(int i = 0 ; i < inorder.length ; i++){ if(inorder[i]== preorder[0]) mid = i; } root.left = buildTree(Arrays.copyOfRange(preorder,1,mid + 1),Arrays.copyOfRange(inorder,0,mid)); root.right = buildTree(Arrays.copyOfRange(preorder,mid + 1,preorder.length),Arrays.copyOfRange(inorder,mid + 1,inorder.length)); return root; } }