本文共 1366 字,大约阅读时间需要 4 分钟。
问题描述
输入某二叉树的前序遍历和中序遍历结果,请重建该二叉树。假设输入的前序遍历和中序遍历结果中都不含重复的数字。例如,给出前序遍历 preorder = [3,9,20,15,7] 和中序遍历 inorder = [9,3,15,20,7],返回如下的二叉树:3 / \ 9 20 / \ 15 7
解决思路
树的相关问题通常可以考虑使用递归的方法来解决。递归法通过分治的思想,逐步划分子树,直到找到单个节点为止。具体来说,我们可以采用以下步骤来重建二叉树:
首先,建立一个映射表,将中序遍历中的节点值与其位置存储起来。这样可以快速找到某个节点在中序遍历中的位置。
然后,通过递归的方式,从前序遍历和中序遍历中依次找到子树的根节点及其左右子树的范围。具体来说:
递归地重建左子树和右子树,直到所有节点都被处理完毕。
代码实现
import java.util.HashMap;import java.util.Map;class Solution { Map map = new HashMap<>(); int[] preorder; public TreeNode buildTree(int[] preorder, int[] inorder) { this.preorder = preorder; for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return trackck(0, 0, preorder.length - 1); } public TreeNode trackck(int rootPreIndex, int inorderLeft, int inorderRight) { if (inorderLeft > inorderRight) { return null; } TreeNode root = new TreeNode(preorder[rootPreIndex]); int rootInIndex = map.get(preorder[rootPreIndex]); root.left = trackck(rootPreIndex + 1, inorderLeft, rootInIndex - 1); root.right = trackck(rootPreIndex + (rootInIndex - inorderLeft + 1), rootInIndex + 1, inorderRight); return root; }} 这个方法的核心思想是利用前序遍历和中序遍历的特点,通过递归的方式分割子树,最终重建出原来的二叉树。
转载地址:http://wxsu.baihongyu.com/