简体   繁体   English

如何在二维矩阵中表示 n 叉树?

[英]How to represent n-ary tree in 2D matrix?

I am trying to represent an n-ary tree in an 2D matrix.我试图在二维矩阵中表示一棵 n 元树。 Not sure how to approach the problem.不知道如何解决这个问题。 This would be some sort of hierarchy.这将是某种层次结构。 I have the root node of the tree我有树的根节点

Example:例子: 在此处输入图像描述

Output:输出: 在此处输入图像描述

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>

You can use the same technique used to represent graph in 2D matrix.您可以使用与在二维矩阵中表示图形相同的技术。 see this article看这篇文章

For this tree the dimension of the matrix will be 11x11.对于这棵树,矩阵的维度将为 11x11。

and the matrix will be like this矩阵将是这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM