【问题标题】:Creating a binary Tree and search function创建二叉树和搜索函数
【发布时间】:2019-10-15 00:21:22
【问题描述】:

我正在创建一个 二叉树 并且只想使用 Search 功能,但我想知道访问了多少个节点才能找到一个值.在搜索功能中。

这是听者文件

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

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

【问题讨论】:

  • TreeNode *&amp;nodePtr 应该是什么意思?你想要一个指针还是一个引用。
  • nodePtr 是指向 TreeNode 结构的指针,也是对指向 TreeNode 结构的指针的引用。这意味着在 nodePtr 上执行的任何操作实际上都是在传递给 nodePtr 的参数上执行的。
  • 我可以看到您是 stackoverflow 的新手。请不要那样改变你的问题。问一件事,如果您有新问题,请创建一个新问题。

标签: c++ data-structures tree binary-search-tree


【解决方案1】:

您的包含错误。

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

只需删除该行,就可以了。

【讨论】:

  • 谢谢你,现在我不知道如何处理 serch 函数,因为它在找到对我的价值之前遇到了多少个节点。
猜你喜欢
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
相关资源
最近更新 更多