根据后序遍历序列和中序遍历序列创建一棵二叉树T[C/C++]

### 构造二叉树算法解析 要根据后序遍历序遍历序列构造二叉树,可以利用递归的思想完成。以下是详细的解析: #### 后序遍历的特点 后序遍历的顺序是左子树 -> 右子树 -> 根节点。因此,在后序遍历数组 `postorder` 的最后一个元素总是当前子树的根节点。 #### 中序遍历的特点 中序遍历的顺序是左子树 -> 根节点 -> 右子树。通过找到根节点的位置,我们可以划分出左子树右子树对应的范围。 #### 算法思路 1. 使用后序遍历中的最后一位作为根节点。 2. 在中序遍历中定位该根节点的位置,从而分割出左子树右子树的部分。 3. 对于左子树部分,重复上述过程;对于右子树部分也如此操作。 4. 基于以上逻辑编写递归函数实现。 下面是具体的 C++ 实现代码: ```cpp #include <iostream> #include <unordered_map> #include <vector> using namespace std; // 定义二叉树节点结构 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: unordered_map<int, int> indexMap; // 存储序遍历中每个值对应索引位置 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { if (inorder.empty()) return nullptr; // 将中序遍历的结果存入哈希表以便快速查找 for (int i = 0; i < inorder.size(); ++i) { indexMap[inorder[i]] = i; } return helper(postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); } private: TreeNode* helper(const vector<int>& postorder, int inLeft, int inRight, int postLeft, int postRight) { if (inLeft > inRight || postLeft > postRight) return nullptr; // 当前子树的根节点是从后序遍历得到的最右边的一个数 int rootValue = postorder[postRight]; TreeNode* root = new TreeNode(rootValue); // 获取根节点在中序遍历中的索引 int pIndex = indexMap[rootValue]; // 左子树长度 int leftSize = pIndex - inLeft; // 递归构建左子树右子树 root->left = helper(postorder, inLeft, pIndex - 1, postLeft, postLeft + leftSize - 1); root->right = helper(postorder, pIndex + 1, inRight, postLeft + leftSize, postRight - 1); return root; } }; ``` 此代码实现了基于后序遍历序遍历重建二叉树的功能[^1]。其中使用了一个辅助函数 `helper` 来处理递归调用,借助哈希表加速了中序遍历中节点位置的查询速度。 --- ### 示例运行 假设输入如下: - 中序遍历:`inorder = [9, 3, 15, 20, 7]` - 后序遍历:`postorder = [9, 15, 7, 20, 3]` 执行结果会返回一棵二叉树,其结构为: ``` 3 / \ 9 20 / \ 15 7 ``` --- ### 时间复杂度分析 - **时间复杂度**:O(n),其中 n 是节点数量。每次递归都会减少一个问题规模的一部分,而哈希表使得寻找根节点的时间降为 O(1)[^2]。 - **空间复杂度**:O(n),主要由递归栈以及存储序遍历映射关系的空间决定。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值