已知一个二叉树的先序遍历序列和中序遍历序列,但其中一些节点的值可能相同。请你返回所有满足条件的二叉树。二叉树在数组中的顺序是任意的。
输入
[1,1,2],[1,2,1]
输出
[{1,1,#,#,2},{1,#,1,2}]
麻烦的是最后构造出的二叉树不唯一了
看起来并不高明,能过但是我没能写出来的代码
class Solution {
public:
vector<TreeNode*> myBuildTree(const vector<int>& preorder,const vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
vector<TreeNode*> res;
if (preorder_left > preorder_right) {
res.push_back(nullptr);
return res;
}
for (int i = inorder_left; i <= inorder_right; i++) {
// 在中序遍历序列中查找可能的根节点的索引
if (inorder[i] == preorder[preorder_left]) {
int size_of_leftsub = i - inorder_left;
vector<TreeNode*> left = myBuildTree(preorder, inorder,preorder_left + 1, preorder_left + size_of_leftsub, inorder_left, i - 1);
vector<TreeNode*> right = myBuildTree(preorder, inorder,preorder_left + size_of_leftsub + 1, preorder_right, i + 1, inorder_right);
for (TreeNode* left_child : left) {
for (TreeNode* right_child : right) {
TreeNode* root = new TreeNode(preorder[preorder_left]);
root->left = left_child;
root->right = right_child;
res.push_back(root);
}
}
}
}
return res;
}
vector<TreeNode*> getBinaryTrees(vector<int>& preOrder, vector<int>& inOrder) {
vector<TreeNode*> res;
int n = preOrder.size();
res = myBuildTree(preOrder,inOrder, 0, n - 1, 0, n - 1);
return res;
}
};
标签:preorder,right,res,中序,vector,二叉树,inorder,前序,left
From: https://www.cnblogs.com/yaocy/p/17001583.html