[英]Preorder traversal of a tree
I have implemented a method to do a preorder traversal of a tree, which is not a binary tree. 我实现了一种方法来对树进行预遍历,该树不是二叉树。 Every parent node of this tree has an array of children, so this is the method I am using: 这棵树的每个父节点都有一个子数组,所以这是我正在使用的方法:
void preorderTraversal(TreeNode tree)
{
if (tree == null)
return;
System.out.print(tree.element + " ");
for(TreeNode child : tree.childern) // children is an Arraylist
{
preorderTraversal(child);
}
}
Sample of linking children nodes to parent "tnAA" 将子节点链接到父“ tnAA”的样本
/* Creating Object of class tree*/
Tree tree = new Tree();
tree.setRoot(tnAA);
TreeNode root2 = tree.getRoot();
/* creating the links between nodes of Tree*/
ArrayList<TreeNode> AA_children = new ArrayList<TreeNode>();
AA_children.add(tnBB);
AA_children.add(tnCC);
AA_children.add(tnDD);
tnBB.parent=tnAA; tnCC.parent = tnAA; tnDD.parent = tnAA;
// Tree
// A
// / | \
// B C D
// /\ |
// E F G
But it only outputs the root node, what's wrong with this method? 但是它仅输出根节点,此方法有什么问题?
Solution: linking children array to each parent : tnAA.setChildern(AA_childern); 解决方案:将子级数组链接到每个父级 :tnAA.setChildern(AA_childern);
You never add anything to any node's childern
list. 您永远不会在任何节点的childern
列表中添加任何内容。 You create an ArrayList called AA_childern
, but it is not connected to the tree, and the tree doesn't know or care that it exists. 您创建了一个名为AA_childern
的ArrayList,但它没有连接到树上,并且树不知道或不在乎它的存在。 Those child nodes need to be added to tnAA.childern
. 这些子节点需要添加到tnAA.childern
。
PS The correct spelling is 'child re n'. PS正确的拼写是'child re n'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.