給定兩種遍歷序列,重構二叉樹,假設無重複值。
以「前序+中序」為例:
「後序+中序」類似,後序最後一個是根節點。
/**
* Definition for binary tree
* struct TreeNode { int val; TreeNode *left; *right; TreeNode(int x):val(x),left(NULL),right(NULL){} };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty()) return nullptr;
return build(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
}
private:
TreeNode* build(vector<int>& pre, vector<int>& in,
int preL, int preR, int inL, int inR) {
if (preL > preR) return nullptr;
int rootVal = pre[preL];
TreeNode* root = new TreeNode(rootVal);
int inRootIdx = inL;
while (in[inRootIdx] != rootVal) inRootIdx++;
int leftSize = inRootIdx - inL;
root->left = build(pre, in, preL+1, preL+leftSize, inL, inRootIdx-1);
root->right = build(pre, in, preL+leftSize+1, preR, inRootIdx+1, inR);
return root;
}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (postorder.empty()) return nullptr;
return build(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
}
private:
TreeNode* build(vector<int>& in, vector<int>& post,
int inL, int inR, int postL, int postR) {
if (inL > inR) return nullptr;
int rootVal = post[postR];
TreeNode* root = new TreeNode(rootVal);
int inRootIdx = inL;
while (in[inRootIdx] != rootVal) inRootIdx++;
int leftSize = inRootIdx - inL;
root->left = build(in, post, inL, inRootIdx-1, postL, postL+leftSize-1);
root->right = build(in, post, inRootIdx+1, inR, postL+leftSize, postR-1);
return root;
}
};
L > R)。O(n^2)(查找根節點為線性),可用哈希表優化至 O(n)。O(h)(遞歸棧),最壞 O(n)。