我正在努力解決這個問題,
給定一個表 BST,包含兩列:N 和 P,其中 N 表示二叉樹中節點的值,P 是 N 的父節點。
撰寫查詢以查找按節點值排序的二叉樹的節點型別。為每個節點輸出以下之一:
Root: If node is root node. Leaf: If node is leaf node. Inner: If node is neither root nor leaf node.
輸入:

期望輸出:
1 Leaf
2 Inner
3 Leaf
5 Root
6 Leaf
8 Inner
9 Leaf
這是我的查詢,誰能告訴我為什么它不起作用?
select case
when P is NULL then CONCAT_WS(" ", N, 'Root')
when N not in (SELECT DISTINCT P FROM BST) then CONCAT_WS(" ", N, 'Leaf')
else CONCAT_WS(" ", N, 'Inner')
end
from BST ORDER BY N ASC;
uj5u.com熱心網友回復:
您NULL在P列內有一個運算式,例如:
1 NOT IN (NULL, 2, 8, 5)
將回傳unknown而不是“預期”結果true(ref)。
解決方案是進行細微的更改,如下所示:
N NOT IN (SELECT P FROM BST WHERE P IS NOT NULL)
或者使用EXISTS查詢:
NOT EXISTS (SELECT * FROM BST AS bst2 WHERE bst2.P = bst.N)
uj5u.com熱心網友回復:
SELECT n,
ELT((1 (2 * (t1.p IS NULL)) (EXISTS (SELECT NULL FROM BST t2 WHERE t1.n=t2.p))), 'Leaf', 'Inner', 'Single', 'Root') type
FROM BST t1
ORDER BY n;
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=287b1de2b2bb532d73619c19bcf8a86b
我再添加一個選項“單一” - 節點同時是根和葉的情況(我的小提琴中的節點 4)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/330812.html
