为什么在 HackerRank 中我得到正确的 mysql 代码的错误答案?

问题描述 投票:0回答:1

在 HackerRank 中,问题“Binary Tree Nodes”指出:

给你一个表BST,包含两列:N和P,其中N表示二叉树中节点的值,P是N的父节点。

Table content

写一个查询来查找二叉树的节点类型,按照节点的值排序。为每个节点输出以下内容之一:

  • Root:如果节点是根节点。
  • Leaf:如果节点是叶节点。
  • Inner:如果节点既不是根节点也不是叶节点。

我的mysql代码是:

select case
            when N in (select P from BST) then
                case
                    when P is null then concat(N,' Root')
                    else concat(N, ' Inner')
                end
            else concat(N,' Leaf')
        end
from BST
order by N;

但是我得到了错误的答案,因为我的输出是:

when N in (select P from BST) then
case
when P is null then concat(N,' Root')
else concat(N, ' Inner')
end
else concat(N,' Leaf')
end
1 Leaf
2 Inner
3 Leaf
4 Inner
5 Leaf
6 Inner
7 Leaf
8 Leaf
9 Inner
10 Leaf
11 Inner
12 Leaf
13 Inner
14 Leaf
15 Root

代替

1 Leaf
2 Inner
3 Leaf
4 Inner
5 Leaf
6 Inner
7 Leaf
8 Leaf
9 Inner
10 Leaf
11 Inner
12 Leaf
13 Inner
14 Leaf
15 Root

为什么会这样?

mysql sql binary-tree
1个回答
0
投票

这是用于 SQL 输入的 HackerRank 解析器中的一个故障(或限制),它显然不能很好地处理换行符。

如果你至少把所有的

case
表达式放在一行上,它就会起作用,就像这样:

select
case when N in (select P from BST) then (case when P is null then concat(N,' Root') else concat(N, ' Inner') end) else concat(N,' Leaf') end
from BST
order by N
© www.soinside.com 2019 - 2024. All rights reserved.