题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
import java.util.*; /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode reConstructBinaryTree(int [] pre, int [] vin) { if (pre == null || pre.length == 0 || vin == null || vin.length == 0) { return null; } // 构造二叉树 TreeNode root = constructBinaryTree(pre, 0, pre.length - 1, vin, 0, vin.length - 1); return root; } /** * 传入前序序列数组,起点和终点 * 传入中序序列数组,起点和终点 * */ private TreeNode constructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { // 递归终止条件 if (startPre > endPre || startIn > endIn) { return null; } // 构建根节点,前序第一个值 TreeNode root = new TreeNode(pre[startPre]); // 遍历中序,找到根节点 for (int index = startIn; index <= endIn; index++) { if (in[index] == pre[startPre]) { // 递归构建左子树,左边数组列表的起终点结算 root.left = constructBinaryTree(pre, startPre + 1, startPre + (index - startIn), in, startIn, index - 1); // 递归构建右子树,右边数组列表的起终点结算 root.right = constructBinaryTree(pre, (index - startIn) + startPre + 1, endPre, in, index + 1, endIn); break; } } return root; } }
解决思想:递归子树遍历,主要注意每段子树的边界索引值
#算法##算法笔记#