简体   繁体   中英

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"

/* 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 called AA_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 to tnAA.childern .

PS The correct spelling is 'child re n'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM