JZ04-重建二叉树
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) { //递归截止条件 if(pre==null||in==null||pre.length==0||in.length==0){ return null; } //主要是防止测试案例 if (pre.length != in.length) { return null; } TreeNode root = new TreeNode(pre[0]); for (int i = 0; i < in.length; i++) { if (pre[0] == in[i]) { root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length)); } } return root; }