簡體   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