英文:
Initialize a tree in inorder?
问题
以下是您要翻译的内容:
tree::tree(const initializer_list<int>& I) {
const int* p1 = I.begin();
root = nullptr;
IL_helper(I, p1, root);
}
void tree::IL_helper(const initializer_list<int>& I, const int* &p1, node* &p2) {
if (p1 == I.end()) {
return;
}
p2 = new node(*p1);
++p1;
IL_helper(I, p1, p2->Lchild);
IL_helper(I, p1, p2->Rchild);
}
如何使用递归的方式根据中序遍历创建一棵树。在我的代码中,我意识到它只会创建左子树。
tree t{1,2,3,4,5,6,7};
cout << t.inOrderT(t.root);
输出:1,2,3,4,5,6,7
英文:
Im using initializer list and helper to create a tree in inorder. for example {1,2,3,4,5,6,7} if I print the tree in inorder traversal it will also give 1,2,3,4,5,6,7.
tree::tree(const initializer_list<int>& I) {
const int* p1 = I.begin();
root = nullptr;
IL_helper(I, p1, root);
}
void tree::IL_helper(const initializer_list<int>& I, const int*& p1, node* & p2) {
if (p1 == I.end()) {
return;
}
p2 = new node(*p1);
++p1;
IL_helper(I, p1, p2->Lchild);
IL_helper(I, p1, p2->Rchild);
}
how to form a tree with inorder traversal with recursion. In my code, I realize it will only have Lchild.
tree t{1,2,3,4,5,6,7} ;
cout << t.inOrderT(t.root);
output: 1,2,3,4,5,6,7
答案1
得分: 0
p2 = new node(*p1);
操作会覆盖 p2
,但它的类型只是 node*
,所以这个赋值不会影响函数外的任何内容。只需将参数更改为 node* &p2
。
另外,我注意到第二个问题 - 在你的示例中没有对输入列表进行二分,所以你构建的树节点将始终只有 Lchild
设置。因为在递归链中的 IL_helper(I, p1, p2->Lchild);
会消耗所有的列表,不会留下任何东西供 Rchild 调用。从技术上讲,如果这是预期的行为(例如,之后可能会重新平衡树),那么这不算是错误,但是吗?
英文:
p2 = new node(*p1);
overwrites the p2
, but its type is just node*
, so this assignment does not affect anything outside of the function. Just change the parameter to node* &p2
.
Also, I see a second problem - in your example is no bisection of the input list - so the nodes of the tree you will construct will always have just the Lchild
set. Because in the recursive chain of IL_helper(I, p1, p2->Lchild);
all of the list will be consumed, leaving nothing left for the Rchild call. It's technically not a bug if that's the intended behavior ( for example, the tree might be re-balanced afterwards ), but is it ?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论