[英]How to represent n-ary tree in 2D matrix?
The table represents a pre-order (depth-first) traversal.该表表示预序(深度优先)遍历。 You can implement it with a recursive function.
您可以使用递归函数来实现它。
Pseudo code:伪代码:
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
Here is an implementation in JavaScript, with output to an HTML table:这是 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.