初始化一个树的中序遍历?

huangapple go评论77阅读模式
英文:

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&lt;int&gt;&amp; I) {
	const int* p1 = I.begin();
	root = nullptr;
	IL_helper(I, p1, root);
}

void tree::IL_helper(const initializer_list&lt;int&gt;&amp; I, const int*&amp; p1, node* &amp; p2) {
	if (p1 == I.end()) {
        return;
    }
	
    p2 = new node(*p1);
    ++p1;
	
    IL_helper(I, p1, p2-&gt;Lchild);
    IL_helper(I, p1, p2-&gt;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* &amp;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-&gt;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 ?

huangapple
  • 本文由 发表于 2023年4月11日 12:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定