标签:
public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder == null || inorder == null || preorder.length != inorder.length || preorder.length == 0) { return null; } int rootVal = preorder[0]; int mid = 0; for (int i = 0; i < inorder.length; i++) { if (inorder[i] == rootVal) { mid = i; break; } } int[] leftPre = Arrays.copyOfRange(preorder, 1, mid + 1); int[] leftIn = Arrays.copyOfRange(inorder, 0, mid); int[] rightPre = Arrays.copyOfRange(preorder, mid + 1, preorder.length); int[] rightIn = Arrays.copyOfRange(inorder, mid + 1, inorder.length); TreeNode root = new TreeNode(rootVal); root.left = buildTree(leftPre, leftIn); root.right = buildTree(rightPre, rightIn); return root; } }
参考:http://www.cnblogs.com/huntfor/p/3883517.html
根据前序序列和中序序列构建树。递归。
105 Construct Binary Tree From Preorder and Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/77rousongpai/p/4513583.html