This commit is contained in:
krahets
2026-08-18 03:09:22 +08:00
parent d8c34d88b5
commit ba5285949b
108 changed files with 237 additions and 229 deletions
@@ -27,12 +27,12 @@ comments: true
根据定义,`preorder``inorder` 都可以划分为三个部分。
- 前序遍历:`[ 根节点 | 左子树 | 右子树 ]` ,例如图 12-5 的树对应 `[ 3 | 9 | 2 1 7 ]`
- 中序遍历:`[ 左子树 | 根节点 右子树 ]` ,例如图 12-5 的树对应 `[ 9 | 3 | 1 2 7 ]`
- 中序遍历:`[ 左子树 | 根节点 | 右子树 ]` ,例如图 12-5 的树对应 `[ 9 | 3 | 1 2 7 ]`
以上图数据为例,我们可以通过图 12-6 所示的步骤得到划分结果。
1. 前序遍历的首元素 3 是根节点的值。
2. 查找根节点 3 在 `inorder` 中的索引,利用该索引可将 `inorder` 划分为 `[ 9 | 3 1 2 7 ]`
2. 查找根节点 3 在 `inorder` 中的索引,利用该索引可将 `inorder` 划分为 `[ 9 | 3 | 1 2 7 ]`
3. 根据 `inorder` 的划分结果,易得左子树和右子树的节点数量分别为 1 和 3 ,从而可将 `preorder` 划分为 `[ 3 | 9 | 2 1 7 ]`
![在前序遍历和中序遍历中划分子树](build_binary_tree_problem.assets/build_tree_preorder_inorder_division.png){ class="animation-figure" }