繁体   English   中英

如何从 BinaryTree 打印出具有连续编号的节点值?

[英]How to print out Node Values from BinaryTree with continuing number?

我正在尝试遍历二叉树并在每个节点前面打印出具有匹配数字节点值 为了更好地理解:我在调用我的方法时打印出以下几行

  1. 11, 2. 33, 3. 10, 4. 14, 5. 27, 3. 31, 4. 32

作为我的方法的目标打印出完全相同的节点顺序前面的数字会增加,这应该表明顺序。 像这样:

  1. 11
  2. 33
  3. 10
  4. 14
  5. 27
  6. 31
  7. 32

直到知道我的方法看起来像这样:

public int mNr(Node k, int Nr) {
        //If the current Node is null, return 0 (currently not making any use of the return)
        if(k == null) {
            return 0;
        } else {
            //If the left Side is not null print out the Left Node with Value 
            if(k.left != null) {
                //increment Nr each time priniting
                System.out.println("Nr: " + ++Nr + " " + k.left.number);
            }
            if(k.right != null) {
                //Same as left Side
                System.out.println("Nr: " + ++Nr + " " + k.right.number);
            }
            //Calling the Method and not incrementing the Nr Parameter because 
            //already incrementing it in the print Statements
            return mNr(k.left, Nr) + mNr(k.right, Nr);
        }
    }

我也不太确定如何使用int -return ,即使知道我没有使用它。 获得正确 Output 的任何建议都会有所帮助。

由于每个递归调用都有自己的Nr变量,它们并不总是具有相同的值。 如果在更深的递归中, Nr递增,这不会影响调用者的Nr版本。

正如您似乎已经暗示的那样,您可以使用返回值向调用者传达Nr的最新值是什么,以便调用者可以更新自己的Nr变量,或者根据调用者的喜好使用它。

这是一个更正:

public int mNr(Node k, int Nr) {
    if(k == null) {
        return 0;
    } else {
        if(k.left != null) {
            System.out.println("Nr: " + ++Nr + " " + k.left.number);
        }
        if(k.right != null) {
            System.out.println("Nr: " + ++Nr + " " + k.right.number);
        }
        // Use the return value from the left-recursion to feed the right-recursion
        return mNr(k.right, mNr(k.left, Nr));
    }
}

话虽如此,这种遍历还有一些其他问题:

  • output中不包含根节点
  • 遍历有一个特殊的顺序:它首先是深度和广度的混合。 选择更流行的遍历会更有意义,例如前序遍历(第一个父节点,然后是左子树,然后是右子树)

因此,这导致以下替代代码:

static public int mNr(Node node, int Nr) {
    if (node == null) {
        return Nr;
    }
    System.out.println("Nr: " + ++Nr + " " + node.number);
    return mNr(node.right, mNr(node.left, Nr));
}

返回用于使方法的结果可用于程序中的进一步评估。 在这种情况下,调用mNr的方法可以使用返回 0 来知道节点是空的,因此针对这种情况生成更合适的 output。

暂无
暂无

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

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