繁体   English   中英

为什么我需要在我的方法上使用包装器

[英]Why do I need to use the wrapper on my method

我一直在研究面试问题,当我完成了找到树的最大深度的问题时,我也想把树打印出来。 回顾我处理的一些旧代码,我找到了 printPostOrder 方法。 我发现如果我删除了包装代码,我就无法使用该方法。 我对这个主题知之甚少,并且明白我需要做更多的研究,但有人可以向我解释为什么它是必要的以及为什么要使用它。 或者可能还有其他一些例子,这样我就可以巩固我对内部发生的事情的理解?

// Java program to find height of tree

// A binary tree node
  class Node {
int val;

Node left, right;

Node(int item) {
    val = item;
    left = right = null;
 }
}

class BinaryTree {
Node root;

/*
 * 
 * Through recursion we get both left and right side
 * depths. Then compare left and right side, pick the bigger one and add one to
 * it to account for the current node.
 */
int maxDepth(Node node) {
    if (node == null)
        return 0;
    else {
        /* compute the depth of each subtree */
        int leftDepth = maxDepth(node.left);
        int rightDepth = maxDepth(node.right);

        int bigger = Math.max(leftDepth, rightDepth);

        return bigger + 1;
    }

}

void printPostorder(Node node) {
    if (node == null)
        return;

    // first recur on left subtree
    printPostorder(node.left);

    // then recur on right subtree
    printPostorder(node.right);

    // now deal with the node
    System.out.print(node.val + " ");
}

// why does this wrapper make the above method function and not without it
void printPostorder() {
    printPostorder(root);
}

public static void main(String[] args) {
    BinaryTree tree = new BinaryTree();

    tree.root = new Node(1);
    tree.root.left = new Node(2);
    tree.root.right = new Node(3);
    tree.root.left.left = new Node(4);
    tree.root.left.right = new Node(5);
    tree.root.left.left.left = new Node(66);
    tree.root.left.left.right = new Node(77);
    tree.root.left.left.left.left = new Node(666);

    System.out.println("Height of tree is : " + tree.maxDepth(tree.root));
    tree.printPostorder();

}
}

严格来说,您不需要单独的void printPostorder()方法,它不接受 arguments; 相反,您可以强制调用者调用void printPostorder(Node node) ,并将树的根作为参数传递:

    tree.printPostorder(tree.root);

但这会导致代码混乱。 调用者希望能够只编写tree.printPostorder()来打印树,而不是仅仅因为printPostorder是如何在内部实现的而必须传入冗余参数。

(顺便说一句,在一个更现实的程序中,我希望void printPostorder()是公共的,而Node rootvoid printPostorder(Node node)都是私有的,以免暴露这种实现细节。)

暂无
暂无

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

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