Tag: 树遍历

遍历Java中二叉树的所有节点

假设我有一个简单的二叉树节点类,如下所示: public class BinaryTreeNode { public String identifier = “”; public BinaryTreeNode parent = null; public BinaryTreeNode left = null; public BinaryTreeNode right = null; public BinaryTreeNode(BinaryTreeNode parent, String identifier) { this.parent = parent; //passing null makes this the root node this.identifier = identifier; } public boolean IsRoot() { return parent == null; } } […]

级别顺序遍历java中的通用树(n-ary树)

(如果你想避免冗长的解释,我正在寻找的是java中generics树(n-ary树)的级别顺序遍历。提供的代码工作并需要级别顺序显示function。一小时但无法找到对通用n-ary树的引用。如果soemone可以帮助我在我的代码之上构建LevelOrderDisplay函数,将会很感激,因为它将帮助我理解我得到的队列错误。谢谢!) 我一直在尝试在工作中实现Autosys作业计划的树表示。 由于每个作业(进程)可以有一个或多个依赖作业,我决定使用n-ary树实现,以便我可以映射流。 我正在使用java集合。 我需要执行级别顺序遍历来显示作业依赖性。 首先打印Root,然后是第1级上的所有节点,然后是第2级上的所有节点,依此类推。 我试图在StackOverflow上搜索超过一个小时,但我遇到的大多数例子都是二叉树。 我明白我需要为此使用队列。 根据我在研究过程中得到的结果,该算法应如下所示:如果错误,请纠正我,如果可能,请为此提供代码。 替代方法也是受欢迎的,但我真正想要的是通用树的简单基本级别遍历。 让我们为通用树实现提供一个资源丰富的线程。 大多数代码已经在运行。 请帮忙。 Algo: 对于每个节点,首先访问节点,然后将其子节点放入FIFO队列。 printLevelorder(tree) 1) Create an empty queue q 2) temp_node = root /*start from root*/ 3) Loop while temp_node is not NULL a) print temp_node->data. b) Enqueue temp_node’s children (first left then right children) to q c) Dequeue a node from […]