平衡二进制树编码
Balance Binary tree Coding
嘿,伙计们,我刚开始在课程中学习二叉树,最近有人问我这个问题。由于我难以置信的糟糕执行和对问题的理解不足,我根本不知道如何解决这个问题。请帮帮我!!!
具有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
}
相关文章:
- 在CRC-16 CCITT中将数据从二进制解码为文本,我应该输入一个码字,使用CRC生成器进行编码
- 为二进制树编码remove()函数
- 如何在C++中将二进制编码十进制转换为 int
- 将二进制编码的无符号字符转换为整数
- 如何在65536字节上编码二进制数据到C 上的WebSocket帧
- 为什么动态链接的二进制显示硬编码为so name
- 在C 中对二进制对象进行编码/解码的标准方法
- C++正在创建二进制搜索树:EXC_BAD_ACCESS错误.算法错误还是编码错误
- 在遗传算法中使用二进制编码是必要的吗
- 网络上的二进制编码
- 无法读取二进制编码的十六进制值
- 如何在算术编码中将双精度转换为其二进制形式?
- Windows NT 二进制可执行文件内部常量字符串编码
- C++ 如何将名称硬编码为二进制
- 平衡二进制树编码
- 如何在C++中表示二进制数(用于霍夫曼编码器)
- 使用字符串类编码二进制数据
- 如果可以用IEEE 754中的二进制格式表示,那么硬编码浮点精确吗
- 将一个文件编码为1/0二进制文件,并在c++中重建原始文件
- 区分哈夫曼二进制头和编码二进制