c# - 打印树并跳过某些值
问题描述
在这里,我有以下代码和打印树结构的输入。我的问题是如何才能使具有“不可用”值的节点和叶子被跳过打印。
namespace Tree{public class TreeNode<T>
{
private T value;
private bool hasParent;
private List<TreeNode<T>> children;
public TreeNode(T value)
{
if (value == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
this.value = value;
this.children = new List<TreeNode<T>>();
}
public T Value
{
get
{
return this.value;
}
set
{
this.value = value;
}
}
public int ChildrenCount
{
get
{
return this.children.Count;
}
}
public void AddChild(TreeNode<T> child)
{
if (child == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
if (child.hasParent)
{
throw new ArgumentException("The node already has a parent");
}
child.hasParent = true;
this.children.Add(child);
}
public TreeNode<T> GetChild(int index)
{
return this.children[index];
}
}
public class Tree<T>
{
private TreeNode<T> root;
public Tree(T value)
{
if (value == null)
{
throw new ArgumentNullException("Cannot insert null value");
}
this.root = new TreeNode<T>(value);
}
public Tree(T value, params Tree<T>[] children) : this(value)
{
foreach (Tree<T> child in children)
{
this.root.AddChild(child.root);
}
}
public TreeNode<T> Root
{
get
{
return this.root;
}
}
private void PrintDFS(TreeNode<T> root, string spaces)
{
if (this.root == null)
{
return;
}
Console.WriteLine(spaces + root.Value);
TreeNode<T> child = null;
for (int i = 0; i < root.ChildrenCount; i++)
{
child = root.GetChild(i);
PrintDFS(child, spaces + " ");
}
}
public void TraverseDFS()
{
this.PrintDFS(this.root, string.Empty);
}
}
public static class TreeExample
{
static void Main()
{
Tree<string> tree =
new Tree<string>("John",
new Tree<string>("Jasmine",
new Tree<string>("Jay"),
new Tree<string>("Unavailable")),
new Tree<string>("Unavailable",
new Tree<string>("Jack"),
new Tree<string>("Jeremy")),
new Tree<string>("Johanna")
);
tree.TraverseDFS();
}
}}
现在它打印 :(John, (Jasmine, (Jay), (Unavailable)), (Unavailable, (Jack, (Jeremy))), (Johanna))
我需要它来打印 :(John, (Jasmine, (Jay)), (Johanna))
所以基本上跳过每个值为“Unavailable”的叶子和每个值为“Unavailable”的节点以及该节点的所有子节点
谢谢 !
解决方案
这应该有效:
private void PrintDFS(TreeNode<T> root, string spaces)
{
if (this.root == null
|| "Unavailable" == root.Value.ToString())
{
return;
}
...
推荐阅读
- java - 如何拆分JavaDStream
并打印该行的第二个单词 - javascript - 是否允许在类的静态属性上使用 super 关键字?
- vue.js - 选项列表中的字体真棒图标未按预期加载(但在选择时)
- javascript - 导航栏不适用于所有部分(html、css、js)
- r - 在函数中使用变量名 [R]
- google-cloud-platform - Google Cloud Platform 上的 VMDK 磁盘映像导入失败
- sql - OPENJSON 中的换行符
- excel - 如何使用字符串变量作为 Workbook 对象的索引?
- android - 我想更快地制作广告 html 代码
- javascript - 哪个 Javascript 事件表示 Angular SPA 已完成页面加载?