题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型一维数组 * @param vinOrder int整型一维数组 * @return TreeNode类 */ public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) { return constructBinaryTree(preOrder,0,preOrder.length-1,vinOrder,0,vinOrder.length); } private TreeNode constructBinaryTree(int[] preOrder,int preStart,int preEnd,int[] vinOrder,int vinStart,int vinEnd){ if(preStart > preEnd) return null; int index = 0; for(int i=vinStart;i<=vinEnd;i++){ if(preOrder[preStart] == vinOrder[i]){ index = i; break; } } int leftSize = index - vinStart; TreeNode root = new TreeNode(preOrder[preStart]); root.left = constructBinaryTree(preOrder,preStart+1,preStart+leftSize,vinOrder,vinStart,index-1); root.right = constructBinaryTree(preOrder,preStart+leftSize+1,preEnd,vinOrder,index+1,vinEnd); return root; } }