c++ - 创建二叉树和搜索函数
问题描述
我正在创建一棵二叉树,只想使用搜索功能,但我想知道访问了多少个节点来查找值。在搜索功能中。
这是听者文件
#ifndef INTBINARYTREE_H
#define INTBINARYTREE_H
class IntBinaryTree
{
private:
struct TreeNode
{
int value; // The value in node .
TreeNode *left; //pointer to left node
TreeNode *right; // Pointer to right child node
};
TreeNode *root;
//private member functions
void insert(TreeNode *&,TreeNode *&);
void displayInOrder(TreeNode *) const;
void displayPreOrder(TreeNode *) const;
void displayPostOrder(TreeNode *) const;
public:
IntBinaryTree()
{
root = nullptr;
}
// Binary search tree
int searchNode(int);
void insertNode(int);
void displayInOrder() const
{
displayInOrder(root);
}
#endif // INTBINARYTREE_H
这是 .cpp 文件,我想知道如果没有找到零值并且如果找到值访问了多少个节点,如何使用搜索功能?
#include "IntBinaryTree.h"
void IntBinaryTree::insert(TreeNode *&nodePtr, TreeNode *&newNode)
{
if (nodePtr == nullptr)
nodePtr=newNode; // insert the node
else if (newNode->value < nodePtr->value) `//search the left branch`
insert(nodePtr->left, newNode);
else
insert(nodePtr->right, newNode); //search the right branch
}
void IntBinaryTree::insertNode(int num)
{
TreeNode *newNode= nullptr; // pointer to a new node
//create a new node and store num in it
newNode = new TreeNode;
newNode->value= num;
newNode->left = newNode->right = nullptr;
//insert the node
insert(root, newNode);
}
int IntBinaryTree::searchNode(int num)
{
TreeNode *nodePtr = root;
while(nodePtr)
{
if (nodePtr->value==num)
{
cout<<"Node found"<<num<<endl;
}
else if (num < nodePtr->value)
nodePtr = nodePtr->left; // look to the left side of the branch if less than the value of the node
else
nodePtr = nodePtr->right; // look to the right side of the if not less than the value .
}
返回0;}
这是主文件
#include <iostream>
#include "IntBinaryTree.h"
using namespace std;
int main()
{
IntBinaryTree tree;
cout << "inserting nodes" << endl;
tree.insertNode(5);
tree.insertNode(8);
tree.insertNode(3);
tree.insertNode(12);
tree.insertNode(9);
cout << "Done.\n";
tree.searchNode(5);
return 0;}
您能否为我编写代码并对其进行编辑并简要解释它是如何工作的?
解决方案
您的包含错误。
您的 main.cpp 中有一个#include "IntBinaryTree.cpp"
。因此,插入成员(和许多其他成员)存在两次。一般规则:永远不要包含 cpp 文件。
只需删除线,你应该没问题。
推荐阅读
- cordova - 科尔多瓦要求在mac中的android失败
- r - 无法将“高效 R 编程”的 Bookdown 源编译为 PDF
- javascript - 你如何为每个 XML 数据
- javascript - Angular 5 NgFor - 循环遍历元素并检测已经渲染的元素
- php - 在 Woocommerce 3 中隐藏特定产品类别的购物车优惠券字段
- three.js - Aframe 轨道控制围绕其中心旋转物体,同时保持其他物体固定
- json - 休息服务响应抛出错误 java.io.IOException: UT010029: Stream is closed
- javascript - 我需要在类中声明实例变量吗?
- android - 如何从firebase android中检索日期子项
- ios - iOS - 当我点击它输入文本时,搜索栏跳到顶部