C++ 在C+;中实现二叉树时出错+;
我试图用一些基本方法编写一个新的BinaryTree类,但我的测试程序似乎不起作用。有人能指出代码有什么问题吗 该方案:C++ 在C+;中实现二叉树时出错+;,c++,class,binary-tree,C++,Class,Binary Tree,我试图用一些基本方法编写一个新的BinaryTree类,但我的测试程序似乎不起作用。有人能指出代码有什么问题吗 该方案: #include "stdafx.h" #include <iostream> #include "BinaryTree.h" using namespace std; int main() { BinaryTree example; example.insertNode(1); cout << example.height(
#include "stdafx.h"
#include <iostream>
#include "BinaryTree.h"
using namespace std;
int main() {
BinaryTree example;
example.insertNode(1);
cout << example.height() << endl;
return 0;
}
#包括“stdafx.h”
#包括
#包括“BinaryTree.h”
使用名称空间std;
int main(){
二叉树示例;
示例:insertNode(1);
cout首先,节点甚至没有分配内存
if (root == NULL) {
root->data = data;
}
首先应该改为
if (root == NULL) {
// Allocate memory to root
root->data = data;
}
在此代码中
int BinaryTree::height(TreeNode* node) {
if (node == NULL) {
return 0;
}
else {
return 1 + max(height(node->left), height(node->right));
}
}
由于example.insertNode(1);
因此,执行将转到else
部分
给你
返回1+max(高度(节点->左)、高度(节点->右));
不检查node->left
或node->right
是否存在。此外,由于您没有使用NULL/nullptr
值初始化node->left
和node->right
值,因此它包含导致意外结果的垃圾请考虑使用调试器逐行遍历代码,以便可以查看发生了什么。如果(root==NULL){root->data=data;}
??您需要首先创建根节点:{root=new TreeNode;root->data=data;}
另外,在TreeNode的定义中,将左和右初始化为nullptr
,并使用nullptr
而不是NULL
。在任何代码中,你都从来没有实际分配过TreeNode
。我认为你应该回顾一下你正在学习的任何教程或课程材料,because动态分配对于动态树是强制性的,迟早。“因为你没有初始化节点->左和节点->右”-甚至节点
。OP的帖子中没有一个树节点
是实际分配的,更不用说正确初始化了。