平衡二进制树编码

Balance Binary tree Coding

本文关键字:编码 二进制 平衡      更新时间:2023-10-16

嘿,伙计们,我刚开始在课程中学习二叉树,最近有人问我这个问题。由于我难以置信的糟糕执行和对问题的理解不足,我根本不知道如何解决这个问题。请帮帮我!!!

具有n个节点的二叉树T被认为是h-balance,如果对于任何节点u在T中,它的两个子树的高度之差最多为h,其中h>=0是一个整数。假设一棵空树的高度为-1。假设每个节点u都有三个字段:u.lc指向u的左子项,如果u没有左子项则u.lc=NULL小孩u.rc指向u的右子项,如果u没有右子项则u.rc=NULL;u.height应设置为以u.为根的树的高度

(a) 给定r指向树的根,用伪代码设计一个算法(或C/C++),以u:height填充每个节点u的高度。

(b) 假设每个节点u的高度存储在u.height中,编写一个算法检查T是否为h平衡。(提示:修改(a)中设计的算法)

这甚至不是伪代码,但应该会对您有所帮助。

如果你更正式地陈述它的条件,它通常会让问题变得更清楚:

a)

  • 叶子的高度是-1
  • 内部节点的高度比其两个子树的最大高度大一个

b)

  • 一片叶子是h平衡的
  • 内部节点是h-balanced当且仅当其两个子树都是h-balance的,并且它们的高度之差至多为h

正如您所看到的,这两个问题遵循相同的模式:一个叶子的情况,以及一个依赖于两个子树的情况。

这是在二叉树上递归的一般形式:

void recurse(t)
{
    if (t is a leaf, i.e. an empty tree)
    {
       handle the leaf case
    }
    else
    {
        do something that depends on 
           recurse(left subtree of t) 
        and 
           recurse(right subtree of t)
    }
}

我将剩下的解决方案作为练习。

这里有一个算法。假设节点结构声明如下:

struct Node {
    Node *l;    // left child
    Node *r;    // right child
    int   h;    // subtree height
};

然后

void CalcHeights(Node *n)
{
    if(n != NULL)
    {
        CalcHeights(n->l);  // calc height in subtrees
        CalcHeights(n->r);
        int hl = n->l ? n->l->h : -1;   // read calculated heights
        int hr = n->r ? n->r->h : -1;
        n->h = (hl > hr ? hl : hr) + 1; // get the bigger one plus 1
    }
}
bool TestBalanced(Node const *n, int h)
{
    if(n != NULL)
    {
        if(! TestBalanced(n->l, h) || ! TestBalanced(n->r, h))
            return false;               // unbalanced subtree...
        int hl = n->l ? n->l->h : -1;   // get subtrees heights
        int hr = n->r ? n->r->h : -1;
        return abs(hl - hr) <= h;   // test the difference against H
    }
    return true;  // empty tree is balanced
}