NC_12_reConstructBinaryTree
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/9/7 */ public class NC_12_reConstructBinaryTree { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return dfs(0, 0, in.length - 1, pre, in); } public TreeNode dfs(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) { if (preStart > preorder.length - 1 || inStart > inEnd) { return null; } //创建结点 TreeNode root = new TreeNode(preorder[preStart]); int index = 0; //找到当前节点root在中序遍历中的位置,然后再把数组分两半 for (int i = inStart; i <= inEnd; i++) { if (inorder[i] == root.val) { index = i; break; } } root.left = dfs(preStart + 1, inStart, index - 1, preorder, inorder); root.right = dfs(preStart + index - inStart + 1, index + 1, inEnd, preorder, inorder); return root; } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } }