问题描述:
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
基本思路:
我之前小学和初中的时候也碰到过这种,题,那个时候就是十分的恐惧,然而现在的我已经具有比以前更强的代码能力,数学思维和编程语言的基础了,今天我们就来攻克它!
其实思路非常简单,无非是:
- 把后序遍历的最后一个节点当做根节点。
- 利用这个根节点,把前序遍历分为两部分。
- 由前序遍历的两部分,又可以得出对应部分在后序遍历中的顺序。
- 递归,利用这两部分返回的节点值作为原来根节点的左右节点。
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
// 处理特殊情况
if (inorder.empty()) return NULL;
// 获得根节点
int root_val = postorder.back();
auto pos_of_root = find(inorder.begin(), inorder.end(), root_val);
TreeNode *root = new TreeNode(root_val);
// 获得左右子树的中序遍历
vector<int> left_inorder(inorder.begin(), pos_of_root); // 左子树的中序遍历
vector<int> right_inorder(++pos_of_root, inorder.end()); // 右子树的中序遍历
// 获得左右字数的后续遍历
vector<int> left_postorder;
int size = left_inorder.size();
for (int i = 0; i < size; ++i) { // 获得左子树的后续遍历
left_postorder.push_back(postorder[i]);
}
vector<int> right_postorder;
for (int i = size; i < postorder.size() - 1; ++i) { // 获得右子树的后续遍历
right_postorder.push_back(postorder[i]);
}
// 递归节点的左右子树
root->left = buildTree(left_inorder, left_postorder);
root->right = buildTree(right_inorder, right_postorder);
// 返回结果
return root;
}
};
不过从明细中可以看出这种做法效率有点低,所以让我们来看看别人是怎么写的。
大牛的代码:
class Solution {
public:
int post_index=0;
vector<int> post;
map<int, int> inorder_map;
TreeNode* buildTree(int in_left, int in_right)
{
// 划分中序遍历来建立子节点
if(in_left == in_right)
return nullptr;
TreeNode* root = new TreeNode(post[post_index]);
int index = inorder_map.find(post[post_index])->second;
post_index--;
root->right = buildTree(index+1, in_right);
root->left = buildTree(in_left, index);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
post = postorder;
post_index = post.size()-1;
if(post_index == -1)
return nullptr;
int idx=0;
// 把中序遍历的元素和索引之间建立映射
for(int i=0; i<inorder.size(); i++)
{
inorder_map.insert(pair<int, int>(inorder[i], idx++));
}
return buildTree(0, inorder.size());
}
};
他的思路:
- 建立了一个map(我觉得可以改为unordered_map),把inorder中的字符和其索引联系起来。这样我们就不需要花时空间来重新建立链表了。
- 基本的思想就是:
- 通过postorder中的最后一个节点建立节点.
- 然后通过该节点在inorder中的位置将其分为两个部分(当然要包含左右区间).
- 最后通过递归求其子节点。
注意指向postorder的指针要不断移动,而且注意递归的顺序。
其他经验:
由于C++支持重载,所以我们不需要担心函数名。