# Write your MySQL query statement below
608. 树节点
给定一个表 tree
,id 是树节点的编号, p_id 是它父节点的 id 。
+----+------+ | id | p_id | +----+------+ | 1 | null | | 2 | 1 | | 3 | 1 | | 4 | 2 | | 5 | 2 | +----+------+
树中每个节点属于以下三种类型之一:
写一个查询语句,输出所有节点的编号和节点的类型,并将结果按照节点编号排序。上面样例的结果为:
+----+------+ | id | Type | +----+------+ | 1 | Root | | 2 | Inner| | 3 | Leaf | | 4 | Leaf | | 5 | Leaf | +----+------+
解释
1 / \ 2 3 / \ 4 5
注意
如果树中只有一个节点,你只需要输出它的根属性。
原站题解
pythondata 解法, 执行用时: 522 ms, 内存消耗: 65.8 MB, 提交时间: 2024-05-27 11:30:25
import pandas as pd def tree_node(tree: pd.DataFrame) -> pd.DataFrame: # 复制输入 DataFrame 以避免修改原始数据 tree_copy = tree.copy() # 使用自定义函数计算节点类型 def get_node_type(row: pd.DataFrame): if pd.isnull(row['p_id']): return 'Root' elif row['id'] in tree_copy['p_id'].unique(): return 'Inner' else: return 'Leaf' tree_copy['Type'] = tree_copy.apply(get_node_type, axis=1) # 选择需要的列并按 id 排序 result_df = tree_copy[['id', 'Type']].sort_values(by='id') return result_df def tree_node2(tree: pd.DataFrame) -> pd.DataFrame: a = tree def tree_(x: pd.DataFrame): if pd.isnull(x['p_id']): return "Root" elif tree['p_id'].isin([x['id']]).any(): # any() 等同或,有一个Turn就返回Ture return 'Inner' else: return "Leaf" a["type"] = tree.apply(tree_, axis=1) return a[['id','type']]
mysql 解法, 执行用时: 490 ms, 内存消耗: 0 B, 提交时间: 2022-06-01 10:12:25
# Write your MySQL query statement below select id, case when p_id is null then 'Root' when id in (select distinct p_id from tree) then 'Inner' else 'Leaf' end as type from tree;
mysql 解法, 执行用时: 810 ms, 内存消耗: 0 B, 提交时间: 2022-05-27 15:01:30
# Write your MySQL query statement below select id, case when p_id is null then 'Root' when id in (select distinct p_id from tree) then 'Inner' else 'Leaf' end as type from tree;