首页 > 解决方案 > 创建二叉树和搜索函数

问题描述

我正在创建一棵二叉树,只想使用搜索功能,但我想知道访问了多少个节点来查找值。在搜索功能中。

这是听者文件

#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;}

您能否为我编写代码并对其进行编辑并简要解释它是如何工作的?

标签: c++data-structurestreebinary-search-tree

解决方案


您的包含错误。

您的 main.cpp 中有一个#include "IntBinaryTree.cpp"。因此,插入成员(和许多其他成员)存在两次。一般规则:永远不要包含 cpp 文件。

只需删除线,你应该没问题。


推荐阅读