题解方法
递归
- 前序遍历的第一个节点为根节点
- 根据根节点将中序遍历划分为 [左子树|根节点|右子树]
- 根据中序遍历中左右子树的节点数将前序遍历划分为 [根节点|左子树|右子树]
核心代码
构建中序遍历索引
1 2 3 4 5
| Map<Integer, Integer> idxMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) { idxMap.put(inorder[i], i); }
|
递归建树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| private TreeNode buildTree(int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd) { return null; } int preRootIdx = preStart; int rootVal = preOrder[preRootIdx]; int inRootIdx = idxMap.get(rootVal); TreeNode root = new TreeNode(rootVal); int preLeftStart = preStart + 1; int leftSize = inRootIdx - inStart; int preLeftEnd = preLeftStart + leftSize - 1; int inLeftStart = inStart; int inLeftEnd = inRootIdx - 1; root.left = buildTree(preLeftStart, preLeftEnd, inLeftStart, inLeftEnd); int preRightStart = preLeftEnd + 1; int preRightEnd = preEnd; int inRightStart = inRootIdx + 1; int inRightEnd = inEnd; root.right = buildTree(preRightStart, preRightEnd, inRightStart, inRightEnd);
return root; }
|
题目来源
剑指 Offer 07. 重建二叉树 - 力扣(LeetCode)