PTA Color the Tree

Color the Tree

There is a kind of balanced binary search tree named red-black tree in the data structure. It has the following 5 properties:
(1) Every node is either red or black.
(2) The root is black.
(3) Every leaf (NULL) is black.
(4) If a node is red, then both its children are black.
(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
For each given binary search tree, you are supposed to tell if it is possible to color the nodes and turn it into a legal red-black tree.

Input Specification

Each input file contains several test cases. The first line gives a positive integer K (≤10) which is the total number of cases. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary search tree. The second line gives the postorder traversal sequence of the tree. All the numbers in a line are separated by a space.

思路

这道题是要找出能够形成Red-Black Tree的树有怎样的结构,那么实际上RB Tree中node的“红”与“黑”的性质就不再非常重要了,而更应该关注树本身的结构性质。我认为在有关树结构的数据结构中,递归是一种非常好的算法,在遍历的查找或者插入等等都可以起到简化思考和代码的作用(当然相应的会增加时间),但是RB Tree的定义却不是一个显式的递归定义方法。所以我很想把RB Tree改写成类似于AVL Tree(Adelson-Velskii-Landis Trees)的定义一样。

1.Tree的左右子树是AVL Tree。
2.Tree的左右子树的高的差的绝对值不超过1。

这种定义方法非常有递归的意味,我希望把RB Tree的定义也写成这样。

1.Tree的左右子树是 RB Tree。
2.Tree的左右子树的黑高不超过1。
3.Tree中没有两个连续的红结点。

这种定义方式弱化了RB Tree的一个重要性质——根结点必须是黑节点,但实际上,如果一个树的根结点是红结点,如果这棵树在忽略该条性质的前提下能够构成RB Tree,那么将这个结点变为黑结点后也一定可以构成红黑树。
有了这样的“好定义”之后再来思考对于性质2、3应该如何应用,针对AVL Tree的性质2,我们是把每个黑结点的高度存下来,然后再考察每个结点的时候,获取它的两个孩子结点的高度进行判定。对于AVL Tree中的结点高度有这样的公式(事实上树结构高度就是这样)。
H ( x ) = { M a x ( H ( c ) ) , for all children of  x } + 1 H ( N U L L ) = − 1 H(x) = \{Max(H(c)),\text{for all children of }x\} + 1\\ H(NULL) = -1 H(x)={

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值