print all root to leaf paths in a binary tree

后端 未结 12 1393
野性不改
野性不改 2020-12-23 14:55

i am trying to print all root to leaf paths in a binary tree using java.

public void printAllRootToLeafPaths(Node node,ArrayList path) 
{
    if(node==null)         


        
12条回答
  •  孤城傲影
    2020-12-23 15:41

    Here is the correct Implementation

    public static > List> printAllPaths(BinaryTreeNode node) {
        List > paths = new ArrayList>();
        doPrintAllPaths(node, paths, new ArrayList());
        return paths;
    }
    
    private static > void doPrintAllPaths(BinaryTreeNode node, List> allPaths, List path) {
        if (node == null) {
            return ;
        }
        path.add(node.getData());
        if (node.isLeafNode()) {
            allPaths.add(new ArrayList(path));   
    
        } else {
            doPrintAllPaths(node.getLeft(), allPaths, path);
            doPrintAllPaths(node.getRight(), allPaths, path);
        }
        path.remove(node.getData());
    }
    

    Here is the test case

    @Test
    public void printAllPaths() {
        BinaryTreeNode bt = BinaryTreeUtil.fromInAndPostOrder(new Integer[]{4,2,5,6,1,7,3}, new Integer[]{4,6,5,2,7,3,1});
        List > paths = BinaryTreeUtil.printAllPaths(bt);
    
        assertThat(paths.get(0).toArray(new Integer[0]), equalTo(new Integer[]{1, 2, 4}));
        assertThat(paths.get(1).toArray(new Integer[0]), equalTo(new Integer[]{1, 2, 5, 6}));
        assertThat(paths.get(2).toArray(new Integer[0]), equalTo(new Integer[]{1, 3, 7}));
    
        for (List list : paths) {          
            for (Integer integer : list) {
                System.out.print(String.format(" %d", integer));
            }
            System.out.println();
        }
    }
    

    Here is the output

    1 2 4
    
    1 2 5 6
    
    1 3 7
    

提交回复
热议问题