问题描述
我正在尝试使用 C++ 类和指针创建二叉树。树正在正确初始化。但是,当我向树添加节点时,不是将它们添加到左子树或右子树,而是覆盖根节点。我尝试打印 inorder 值以检查节点是否正确添加,但这也不会打印任何内容。 这是相同的代码。
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
using namespace std;
class Node{
private:
Node *left;
Node *right;
public:
int number;
Node(int number){
this->number = number;
this->left = NULL;
this->right = NULL;
}
void set_left_node(Node *node){
this->left = node;
}
void set_right_node(Node *node){
this->right = node;
}
Node* read_left_node(){
return this->left;
}
Node* read_right_node(){
return this->right;
}
};
class Binary_Tree{
public:
Node *root;
Binary_Tree(){
this->root = NULL;
}
Node* read_root(){
return this->root;
}
Node* insert_node(Node *root,Node node){
if(!root){
root = &node;
cout << "Inserted " << node.number << " " << root << endl;
return root;
}
else{
cout << "Root and node values " << root->number << " " << node.number << endl;
if(root->number < node.number){
root->set_right_node(insert_node(root->read_right_node(),node));
}
else{
root->set_left_node(insert_node(root->read_left_node(),node));
}
}
return root;
}
void inorder(Node *root){
if (root != NULL){
inorder(root->read_left_node());
cout<<root->number<<" ";
inorder(root->read_right_node());
}
}
};
int main(){
Binary_Tree bt = Binary_Tree();
bt.root = bt.insert_node(bt.root,Node(34));
bt.root = bt.insert_node(bt.root,Node(17));
bt.root = bt.insert_node(bt.root,Node(56));
cout << "Inorder" << endl;
bt.inorder(bt.root);
return 0;
}
输出:
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)