简体   繁体   中英

Traversing a tree, but each node visited should visit every node underneath

I am traversing a tree, which is easy and I know how to do this. However, I want to visit each node beneath the current node each iteration. I'm not sure I'm being clear so I will try to illustrate this:

        A
      /   \
     B     C
    / \   / \
   D   E F   G

1st iteration: Node is A: visits B, C, D, E, F, G 2nd iteration: Node is B: visits D, E 2nd iteration: Node is D: visits F, G

I tried writing this as a normal traversal as so:

    public static void addCodes(Message root)
    {
         if (root.getLeftChild() != null){
               root.getLeftChild().setCode(root.getLeftChild().getCode() + "0");
               addCodes(root.getLeftChild());
         }
         if (root.getRightChild() != null) {
               root.getRightChild().setCode(root.getRightChild().getCode() + "1");
               addCodes(root.getRightChild());

         }
    }

but this obviously does not work. Each node is visited one time. I understand why, I just don't know how to fix it. If this were iterative, it would be nested loops. What's the recursive equivalent of this?

I figured it out.

public static void addCodes(Message root)
{
     if (root.getLeftChild() != null){
           root.getLeftChild().setCode(root.getLeftChild().getCode() + "0");
           addCodes(root.getLeftChild());
     }
     if (root.getRightChild() != null) {
           root.getRightChild().setCode(root.getRightChild().getCode() + "1");
           addCodes(root.getRightChild());

     }
}

public static void addCode(Message root)
{
     if (root.getLeftChild() != null){
           addCodes(root.getLeftChild());
           addCode(root.getLeftChild());
     }
     if (root.getRightChild() != null) {
           addCodes(root.getRightChild());
           addCode(root.getRightChild());
     }
}

Main calls addCode.

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