106. 从中序与后序遍历序列构造二叉树
题目描述
根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
题解:
中序遍历:左子树 根节点 右子树
后序遍历:左子树 右子树 根节点
所以,在中序遍历中找到根节点位置,然后递归构建左右子树就行。跟 从前序与中序遍历序列构造二叉树 思路一致。
时间复杂度: O ( n 2 ) O(n^2) O(n2)
额外空间复杂度: O ( n ) O(n) O(n)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void build( TreeNode*& root, int l1, int r1, int l2, int r2, vector<int>& inorder, vector<int>& postorder ) {
if ( l1 > r1 ) return;
int p;
for ( p = l1; inorder[p] != postorder[r2]; ++p );
int gap = p - l1;
root = new TreeNode( postorder[r2] );
build( root->left, l1, p - 1, l2, gap + l2 - 1, inorder, postorder );
build( root->right, p + 1, r1, gap + l2, r2 - 1, inorder, postorder );
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode *root = nullptr;
build ( root, 0, inorder.size() - 1, 0, inorder.size() - 1, inorder, postorder );
return root;
}
};
/*
时间:36ms,击败:44.08%
内存:24.8MB,击败:40.43%
*/
建树过程中查找根节点位置可以使用哈希表优化:
时间复杂度: O ( n ) O(n) O(n)
额外空间复杂度: O ( n ) O(n) O(n)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> hash;
void build( TreeNode*& root, int l1, int r1, int l2, int r2, vector<int>& inorder, vector<int>& postorder ) {
if ( l1 > r1 ) return;
int p = hash[postorder[r2]];
int gap = p - l1;
root = new TreeNode( postorder[r2] );
build( root->left, l1, p - 1, l2, gap + l2 - 1, inorder, postorder );
build( root->right, p + 1, r1, gap + l2, r2 - 1, inorder, postorder );
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode *root = nullptr;
for ( int i = 0; i < inorder.size(); ++i )
hash[inorder[i]] = i;
build ( root, 0, inorder.size() - 1, 0, inorder.size() - 1, inorder, postorder );
return root;
}
};
/*
时间:12ms,击败:98.12%
内存:25.1MB,击败:39.99%
*/