Print all paths from root to leaf in a Binary tree

后端 未结 5 1717
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 17:27

Here is the code I wrote to print all paths of a Binary tree from root to leaf:

public static void printRootToLeaf(Node1 root, List list) {
           


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 18:07

    Here is a simpler example.

    Node1 root = new Node1(1);
    root.left = new Node(2);
    root.right = new Node(3);
    

    With the expected result

    [1,2]
    [1,3]
    

    And actual result

    [1,2]
    [1,2,3]
    

    When you first call printRootToLeaf, List is empty. You add 1 to it, and call printRootToLeaf on the left branch. Within that call, you add 2 to the list, and print [1,2]. You then return to the first call, but 2 is still in the list! You then call printRootToLeaf on the right branch. Within that call, you add 3 to the list, and print [1,2,3].

    Changes made to the list while recursing down the left branch shouldn't propogate to the list passed down the right branch. The easiest way to address this is to make copies of the list each time:

    printRootToLeaf(root.left, copy(list));
    printRootToLeaf(root.right, copy(list));
    

    The actual method of copying the list will vary depending upon what language you're using.

提交回复
热议问题