提问人:stackUnderflow 提问时间:12/14/2022 最后编辑:stackUnderflow 更新时间:12/15/2022 访问量:217
如何在二维矩阵中表示n-ary树?
How to represent n-ary tree in 2D matrix?
答:
1赞
trincot
12/15/2022
#1
该表表示预序(深度优先)遍历。您可以使用递归函数来实现它。
伪代码:
function dfs(children, row=0, col=0):
if no children:
return row + 1 # It is a leaf
for each child in children:
output child.label in table(row, col)
row = dfs(child.children, row, col + 1)
return row # It was not a leaf
下面是一个 JavaScript 中的实现,输出到 HTML 表:
function output(label, row, col) {
document.querySelector("table").rows[row].cells[col].textContent = label;
}
function dfs(children, row=0, col=0) {
if (!children?.length) return row + 1; // End of path
for (const child of children) {
output(child.label, row, col);
row = dfs(child.children, row, col + 1);
}
return row; // It was not a leaf
}
// Example tree:
const forest = [
{ "label": "a", "children": [
{ "label": "b", "children": [
{ "label": "j" },
{ "label": "k" },
]},
{ "label": "c" },
{ "label": "d", "children": [
{ "label": "e" },
{ "label": "f", "children": [
{ "label": "h" },
{ "label": "i" },
]},
{ "label": "g" },
]}
]}
];
dfs(forest);
table { border-collapse: collapse; width: 100%; }
table td { border: 1px solid; width: 20%; padding-left: 10px }
tr { height: 25px; v-align: middle; }
<table>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
评论