题解 | #重建二叉树#
重建二叉树
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) { // write code here return build(preOrder, vinOrder, 0, 0, vinOrder.length - 1); } private TreeNode build(int[] preOrder, int[] inOrder, int preStart, int inStart, int inEnd) { if (inEnd < inStart) { return null; } int rootVal = preOrder[preStart]; TreeNode root = new TreeNode(rootVal); int index = 0; for(int i = inStart; i <= inEnd; i++) { if (inOrder[i] == rootVal) { index = i; break; } } int len = index - inStart; root.left = build(preOrder, inOrder, preStart + 1, inStart ,index - 1); root.right = build(preOrder, inOrder, preStart + len + 1, index + 1, inEnd); return root; } }
递归地对左子树和右子树进行构建
#java#