简体   繁体   English

遍历一棵树,但是访问的每个节点都应访问其下方的每个节点

[英]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 第一次迭代:节点为A:访问B,C,D,E,F,G第二次迭代:节点为B:访问D,E第二次迭代:节点为D:访问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. 主要调用addCode。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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