gpt4 book ai didi

c++ - 原始树的子树

转载 作者:行者123 更新时间:2023-11-28 08:13:33 25 4
gpt4 key购买 nike

我在尝试执行以下操作时遇到了问题:(1) 找到原树根的左子树中最大的info字段(2) 在原树的根的右子树中找到最小的信息字段。

我的代码可以编译,但在执行时出现错误,我不清楚我的 maxleftsubtree() 和 minrightsubtree() 函数中发生了什么。如有任何建议,我们将不胜感激。

我当前的代码:

#include <iostream>
#include <string>

using namespace std;

class Tnode {
public:
Tnode *left;
string info;
Tnode *right;
Tnode(string info = "", Tnode* left = NULL, Tnode* right = NULL) :
info(info), left(left), right(right) {}
};
class BST {
public:
BST() : theroot(NULL) {}
void insert(string x);
void inorderprint();
void preorderprint();
void postorderprint();
void maxstring();
void minstring();
void maxleftsubtree();
void minrightsubtree();
private:
void inorderprint(Tnode *p);
void preorderprint(Tnode *p);
void postorderprint(Tnode *p);
void maxstring(Tnode *p);
void minstring(Tnode *p);
void maxleftsubtree(Tnode *p);
void minrightsubtree(Tnode *p);
void insertleft(Tnode *place, string newval);
void insertright(Tnode *place, string newval);
Tnode *theroot;
};

// add a new node (with x as info) to tree that has theroot as root
void BST::insert(string x)
{
// if the tree is initially empty, put x at the root
if (theroot==NULL) {
theroot = new Tnode(x);
return;
}

Tnode *p, *q;

// otherwise, find where x belongs in the tree
p = theroot;
q = theroot;
while ( q != NULL) {
p = q;
if (x < p-> info)
q = p-> left;
else
q = p-> right;
}

// to get here, we found the correct place to store x,
// as a child of node p Q: is it left or right?

if (x < p-> info)
insertleft(p,x);
else
insertright(p,x);

return;

}

//insert a new node (with info newval) as left child of place
void BST::insertleft(Tnode *place, string newval)
{
Tnode *p = new Tnode(newval);

place -> left = p;
return;

}

//insert a new node (with info newval) as right child of place
void BST::insertright(Tnode *place, string newval)
{
Tnode *p = new Tnode(newval);

place -> right = p;
return;

}
......................
...............
...............

//
//
void BST::maxleftsubtree()
{
maxleftsubtree(theroot);
}

//
//
void BST::minrightsubtree()
{
minrightsubtree(theroot);
}

.....................................
.................................
.........................

//
//
void BST::maxleftsubtree(Tnode *p)
{
while (p -> left)
p = p -> right;
cout << p -> info << " \n";
return;
}

//
//
void BST::minrightsubtree(Tnode *p)
{
while (p -> right)
p = p -> left;
cout << p -> info << " \n";
return;
}

最佳答案

您的 maxleftsubtree(maxtrightsubtree) 函数有错误。你应该先选择根的左(右)子树,沿着右(左)枝走到尽头。这是修改后的版本:

void BST::maxleftsubtree(Tnode *p)
{
Tnode* left = NULL;
if (p != NULL) {
left = p->left;
}
if (left != NULL) {
while (left->right)
left = left -> right;
cout << left -> info << " \n";
}
return;
}

关于c++ - 原始树的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com