1 题目描述
给出一棵树的中序遍历和后序遍历,请构造这颗二叉树
注意:
保证给出的树中不存在重复的节点
2 解题思路
就是数据结构课本里图示方法的代码版。
3 代码实现
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param inorder int整型vector
* @param postorder int整型vector
* @return TreeNode类
*/
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return dfs(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode* dfs(vector<int>& inorder, int in_begin, int in_end,
vector<int>& postorder, int post_begin, int post_end){
if(in_begin > in_end) return NULL;
TreeNode* root = new TreeNode(postorder[post_end]);
int mid;
for(mid = in_begin; mid <= in_end; mid++)
if(inorder[mid] == root->val)
break;
int left_size = mid - in_begin;
root->left = dfs(inorder, in_begin, mid - 1, postorder, post_begin, post_begin + left_size - 1);
root->right = dfs(inorder, mid + 1, in_end, postorder, post_begin + left_size, post_end - 1);
return root;
}
};
4 运行结果
运行时间:4ms
占用内存:540k