LeetCode 106. 已知中序和后序遍历构建二叉树
题目
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思考
举个例子,如下图中的二叉树:
中序遍历为:21435
后序遍历为:24531
还原树的方法:
1. 后序遍历中最后一个为树(或子树)的根,即为1;
2. 用根将中序遍历分为左子树的中序遍历(2)和右子树的中序遍历(435);
3. 按照中序遍历得到左右子树的元素后将后序遍历也分为左子树的后序遍历(2)和右子树的后序遍历(453);
4. 对于左右子树的中序遍历和后序遍历分别进行第一步操作,直到得到结果的二叉树。
我的答案
根据递归的思想得出:
c++
/**
* 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.size() == 0) {
return NULL;
}
int rootNum = postorder.back();
TreeNode* root = new TreeNode(rootNum);
if (inorder.size() == 1) {
return root;
}
bool left1 = true;
vector<int>* inorderLeft = new vector<int>;
vector<int>* inorderRight = new vector<int>;
vector<int>* postorderLeft = new vector<int>;
vector<int>* postorderRight = new vector<int>;
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == rootNum) {
left1 = false;
} else if (left1) {
inorderLeft->push_back(inorder[i]);
postorderLeft->push_back(postorder[i]);
} else {
inorderRight->push_back(inorder[i]);
postorderRight->push_back(postorder[i - 1]);
}
}
// 释放内存
vector<int>().swap(inorder);
vector<int>().swap(postorder);
root->left = buildTree(*inorderLeft, *postorderLeft);
root->right = buildTree(*inorderRight, *postorderRight);
return root;
}
};
上述方法效率较低,应该避免new新的vector,可以用传下标参数(用find函数找出根元素位置)来实现。