遍历对象的树在C#

编程入门 行业动态 更新时间:2024-10-07 12:24:48
本文介绍了遍历对象的树在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有个树由多个对象,其中每个对象具有一个名称(字符串),编号(int)和可能的子女的阵列,其是相同类型的。我该如何去通过整个树,并打印出所有的ID和姓名?

I have a tree that consists of several objects where each object has a name (string), id (int) and possibly an array of children, that are of the same type. How do I go through the entire tree and print out all of the ids and names?

我是新来的编程坦率地说,我有麻烦缠绕我的头围绕这一点,因为我不知道有多少水平有。现在,我使用foreach循环来获取父对象正下方腐烂,把这意味着我不能让孩子。

I'm new to programming and frankly, I'm having trouble wrapping my head around this because I don't know how many levels there are. Right now I'm using a foreach loop to fetch the parent objects directly below rot, put this means I cannot get the children.

推荐答案

这是算法,使用递归是这样的:

An algorithm which uses recursion goes like this:

printNode(Node node) { printTitle(node.title) foreach (Node child in node.children) { printNode(child); //<-- recursive } }

下面是一个版本,这也将跟踪如何深度嵌套的递归(即我们是否要打印的根的孩子,大儿,大 - 大 - 儿童,等等。):

Here's a version which also keeps track of how deeply nested the recursion is (i.e. whether we're printing children of the root, grand-children, great-grand-children, etc.):

printRoot(Node node) { printNode(node, 0); } printNode(Node node, int level) { printTitle(node.title) foreach (Node child in node.children) { printNode(child, level + 1); //<-- recursive } }

更多推荐

遍历对象的树在C#

本文发布于:2023-11-30 06:40:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!