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"
/* 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);
You never add anything to any node's
childern
list. You create an ArrayList calledAA_childern
, but it is not connected to the tree, and the tree doesn't know or care that it exists. Those child nodes need to be added totnAA.childern
.P.S. The correct spelling is 'children'.