[英]Inserting nodes in a Binary Tree recursively?
I am trying to insert nodes in a binary tree recursively, but the code is only doing the root node and it's left and right children.我试图递归地在二叉树中插入节点,但代码只执行根节点,它是左右子节点。 I am trying to figure out how to get past that point.我正在努力弄清楚如何克服这一点。
I have already tried different implementations, using queues, doing level order insert.我已经尝试过不同的实现,使用队列,进行级别顺序插入。 I believe the problem is due to the fact that in my main function I only call with root, and if that is the problem, how would I go about calling with the left and right childs.我相信问题是由于在我的主函数中我只用 root 调用,如果这是问题,我将如何用左右孩子调用。
Main Function:主功能:
int main() {
treenode* root = new treenode();
for(int a = 1; a < 15; a++) {
insert(root, a);
}
cout << "Height: " << height(root) << endl;
cout << "Printed Tree: " << endl;
for(int a = 0; a <= height(root); a++) {
printGivenLevel(root, a); //Print every level
cout << endl;
}
return 0;
}
Here is my insert function:这是我的插入功能:
void insert(treenode*& node, int val) {
if(node == nullptr) {
node = new treenode(val);
return;
}else{
if(node->left == nullptr) {
insert(node->left, val);
}else{
insert(node->right, val);
}
}
}
A treenode has a value, a left child and right child:一个树节点有一个值,一个左孩子和右孩子:
struct treenode {
//The value of the node
int value;
//Pointers to the left and right children
treenode *left, *right;
//Constructor with values;
treenode(int val=0, treenode *l = nullptr, treenode *r = nullptr) : value(val), left(l), right(r) {};
};
I would expect the result to be something like so:我希望结果是这样的:
0 0
1 2 1 2
3 4 5 6 3 4 5 6
7 8 9 10 11 12 13 14 7 8 9 10 11 12 13 14
But my actual output is only:但我的实际输出仅为:
0 0
1 2 1 2
Thanks in advance提前致谢
... but the code is only doing the root node and it's left and right children. ...但代码只做根节点,它是左右孩子。 I am trying to figure out how to get past that point.我正在努力弄清楚如何克服这一点。
I find no error in your treenode::insert, your problem might be in some other code you do not show.我发现您的 treenode::insert 中没有错误,您的问题可能出在您未显示的其他代码中。 For example, you did not provide "height(root)" or "Printed Tree" info.例如,您没有提供“高度(根)”或“印刷树”信息。 I could not diagnose them.我无法诊断他们。
I have provided some alternatives for various ideas.我为各种想法提供了一些替代方案。 see "dump()" and "height()" and "size()".参见“dump()”和“height()”和“size()”。
Note: "dump()" is none of pre, in-, or post- order, because the sorted input creates unbalance tree displays (they are worst-case-unbalanced).注意:“dump()”不是前序、中序或后序,因为排序的输入会创建不平衡的树显示(它们是最坏情况下的不平衡)。 I found this display the easiest to review.我发现这个显示器最容易查看。
Perhaps the following will help you diagnose your mistakes.也许以下内容可以帮助您诊断错误。 Good luck.祝你好运。
Note the use of "if(false) cout << ...".注意“if(false) cout << ...”的使用。 These are diagnostic output which might provide some insights by enabling them, and / or adding such items to your code.这些是诊断输出,可以通过启用它们和/或将此类项目添加到您的代码中来提供一些见解。
Did you try your debugger yet?你试过你的调试器了吗?
#include <chrono> // short form names----vvvvvvv
typedef std::chrono::high_resolution_clock HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point Time_t; // std-chrono-hi-res-clk-time-point
typedef std::chrono::nanoseconds NS_t; // std-chrono-nanoseconds
using namespace std::chrono_literals; // suffixes like 100ms, 2s, 30us
using std::chrono::duration_cast;
#include <iostream>
using std::cout, std::endl, std::flush;
#include <iomanip>
using std::setw;
namespace DTB
{
class treenode
{
friend class T920_t;
int value; //The value of the node
treenode *left, *right; //Pointers to the left and right children
//Constructor with values;
treenode(int val=0, treenode *l = nullptr, treenode *r = nullptr)
: value(val), left(l), right(r) { ctor('A'); };
void ctor(char kar) {
if (left) left->ctor(kar);
{
if(false) // diagnostic
cout << "\n ctor: " << " " << kar
<< " val: " << setw(3) << value << flush;
}
if(right) right->ctor(kar);
}
void insert ( treenode*& node, int val)
{
if(node == nullptr)
{
node = new treenode(val);
if (false) node->dump(); // diagnostic
return;
}
else
{
if(node->left == nullptr)
{
insert(node->left, val);
if (false) node->dump(); // diagnostic
}
else
{
insert(node->right, val);
if (false) node->dump(); // diaagnostic
}
}
}
int height(int lvl = 1)
{
static int maxHeight = 0;
if (left) left->height (lvl+1);
if(right) right->height (lvl+1);
if (lvl > maxHeight) maxHeight = lvl;
return maxHeight;
}
int size()
{
int count = 1; // this element
if (left) { count += left->size(); };
if(right) { count += right->size(); }
return count;
}
void dump(int lvl=0)
{
if (left) left->dump (lvl+1);
if(right) right->dump (lvl+1);
{
cout << "\n " // << lvl
<< setw(3*lvl) << ' '
<< value << flush;
}
}
}; // class treenode
typedef treenode Node_t; // shorter name for user-defined-type
class T920_t
{
public:
int operator()(int argc, char* argv[]) { return exec(argc, argv); }
private:
int exec(int , char** )
{
int retVal = 0;
Time_t start_ns = HRClk_t::now();
Node_t* root = new Node_t(); // 1st node
for(int v = 1; v < 21; ++v) { // 20 more
root->insert(root, v);
}
cout << "\n\n size : " << root->size() // element count
<< " maxHeight : " << root->height()
<< endl;
dumpAll(root);
for(int v = 1; v < 11; ++v) { // 10 more
root->insert(root, v);
}
cout << "\n\n size : " << root->size() // element count
<< " maxHeight : " << root->height()
<< endl;
dumpAll(root);
auto duration_ns = duration_cast<NS_t>(HRClk_t::now() - start_ns).count();
cout << "\n\n\n T920_t::exec() duration "
<< duration_ns << " ns "
<< " cpluplus vers : " << __cplusplus << std::endl;
return retVal;
}
void dumpAll (Node_t*& node)
{
cout << "\n dumpAll(): ";
node->dump();
cout << endl;
}
}; // class T920_t
} // namespace DTB
int main(int argc, char* argv[]) { return DTB::T920_t()(argc, argv); }
A partial output is:部分输出是:
size : 21 maxHeight : 11
dumpAll():
1
3
5
7
9
11
13
15
17
19
20
18
16
14
12
10
8
6
4
2
0
size : 31 maxHeight : 16
dumpAll():
1
3
...
10
8
6
4
2
0
T920_t::exec() duration 271095 ns cpluplus vers : 201703
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.