【问题标题】:C++ binary tree with min heap具有最小堆的 C++ 二叉树
【发布时间】:2018-10-22 08:21:39
【问题描述】:

我正在尝试在树中创建一个最小堆,但是我是新来的,现在我已经有两个星期的时间来回移动指针和地址了,

所以我正在制作这样的结构:

struct node{
    int data;
    node* left;
    node* right;
};

然后是这样的插入函数:

void Insert(int dataii){
    node* new_node = new node();
    new_node->data = dataii;
    new_node->left = new_node->right = NULL;
}

好的,现在是我的问题开始时,如何连接节点以使它们成为树。

我正在考虑使用一个数组来存储数组 [0] 中的 new_nodes 的数量,然后是数组 [1] 等等,将它们与 new_node->data 和地址的价值联系起来。

但我似乎没有找到一个有效的代码来完成这项工作。我的目标是制作一个最小堆的二叉树,但我还不能做这棵树。

一旦每个父母最多有两个孩子,并且在插入时总是从左到右。

如果有人能告诉我如何前进,谢谢。 蒂亚戈

【问题讨论】:

  • 通常,像Insert 这样的函数需要指定插入节点的位置。作为参数或作为成员函数。与英语非常相似,您通常无法在不指定 where 的情况下插入内容。
  • 您是在 c 还是 c++ 中尝试这个?如果在 c 中,则将 Insert func 放入要插入的节点中,如果在 c++ 中,请尝试将 node 设为一个类。
  • 将堆存储为线性数组实际上更容易,而不是带有指针的实际二叉树。

标签: c++ binary heap min


【解决方案1】:

这应该能让你继续前进。

#include<iostream>

using namespace std;

class Node{
public:
    int data;
    Node *left, *right;

    Node(int data);
    ~Node();
    int count();
    void insert(Node *n);
    void print(const int indent, const char* note);
};

Node::Node(int data) {
   this->data = data;
   this->left = this->right = NULL;
}

Node::~Node(){
    if (this->left != NULL) delete this->left;
    if (this->right != NULL) delete this->right;
}

int Node::count() {
    int r = 1;
    if (this->left != NULL) r += this->left->count();
    if (this->right != NULL) r += this->right->count();
    return r;
}

void Node::insert(Node* n){
    if (this->left == NULL) this->left = n;
    else if (this->right == NULL) this->right = n;
    else if (this->left->count() > this->right->count()) this->right->insert(n);
    else this->left->insert(n);
}

void Node::print(const int indent=0, const char *note="") {
    for(int i = 0; i < indent; i++) cout << " ";
    cout << this->data << " " << note << endl;
    if (this->left != NULL) this->left->print(indent+1, "(l)");
    if (this->right != NULL) this->right->print(indent+1, "(r)");
}

int main(int argc, char const *argv[]) {
    Node *root = new Node(0);
    for (int i = 1; i <= 10; i++) root->insert(new Node(i));
    root->print();
    delete root;
    return 0;
}

See full project with implemented min/max heaps

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 2021-12-19
    • 2014-02-02
    • 2016-07-12
    • 2014-12-07
    • 1970-01-01
    • 2014-12-09
    • 2014-08-07
    相关资源
    最近更新 更多