【问题标题】:how to create a full binary tree with empty nodes如何创建具有空节点的完整二叉树
【发布时间】:2017-04-15 12:03:45
【问题描述】:

我正在将 2 棵模板 AVL 树合并为 1 棵树,其复杂度为两棵树中节点的 total 数量(这很棘手) - 正确的算法是构建一棵完整的二叉树total 的节点数量 - 如果 total 等于 2 的幂减去 1,或者创建一个完整的二叉树,其节点数比总的多(下一个 2 的幂)并切掉不必要的叶子(总和 2 的下一个幂之间的差异)而节点也是模板并且应该为空。 如何在没有任何键比较的情况下构建具有空节点的完整二叉树(我不能有任何键,因为节点是模板)?

我的模板节点是:

class avl_node{
private:
    friend class avl_tree;
    //design to contain dinamically allocated key and data only!
    //assumption- every node uses it's own data and key- no data or key are the
    //same memory for different nodes!
    Key *key;
    T *data;
    avl_node *parent;
    avl_node *right;
    avl_node *left;
    int height;
    int balance;
    int maxHeight(int h1,int h2){
        return (h1 > h2) ? h1:h2;
    }

public:
    avl_node(Key* key=nullptr, T* data=nullptr): key(key),data(data),right(nullptr),left(nullptr),parent(nullptr),height(0),balance(0){}
    //no setKey since this is an invariant from node creation
    virtual ~avl_node(){
        delete key;
        delete data;
        delete right;
        delete left;
    }
    virtual bool insert( Key* key,  T* data,avl_node *& to_fix_from);
    virtual avl_node * findNode(const Key& key);
    virtual void updateStats() {
        if(left && right){
            height=maxHeight(left->height,right->height)+1;
            balance=left->height-right->height;
            return;
        }
        if(!left && right){
            height=right->height+1;
            balance=-right->balance;
            return;
        }
        if(left &&!right){
            height=left->height+1;
            balance=left->height;
            return;
        }
        this->height=0;
    }

};

问题是 - 键是一个模板参数 - 所以我不能决定,例如,对所需的节点数量进行 for 循环并创建一些简单的键(根据 for-loops 的计数器)并插入它- 因为插入需要一些选项来比较。

我正在编辑问题:我发现 here ,我可以动态分配一个空节点数组,并递归地分配每个节点左右为二进制搜索(在数组索引)。 新问题:我可以从指向该节点的 a 指针中逐一释放每个节点吗?尽管它们是在数组中分配的?因为我想只保留一个根并将其视为具有兼容删除功能的树。

【问题讨论】:

  • 更详细地解释您的问题。它与 C++ 有什么关系?
  • “节点是模板”是什么意思?你知道如何以你想要的方式构造 one 节点吗?如果节点总数不是 2^n-1 怎么办?
  • 我现在将对其进行编辑,查找并感谢@KirillKobelev

标签: c++ templates binary-tree


【解决方案1】:

这个问题并不是你想要达到的目标。构建一个完整的空树相对简单。此时您不需要任何密钥。它们都将为 NULL。你可以这样做:

avl_node *avl_node::BuildAvlSubtree(int height_needed)
{
    if (height_needed <= 0)
        return nullptr;
    auto node = new avl_node();
    node->left = BuildAvlSubtree(height_needed-1);
    node->right = BuildAvlSubtree(height_needed-1);
    return node;
}

这个函数应该是avl_node 类的静态成员,因为它访问私有成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多