print all root to leaf paths in a binary tree

后端 未结 12 1390
野性不改
野性不改 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:51

    /* Given a binary tree, print out all of its root-to-leaf
       paths, one per line. Uses a recursive helper to do the work.*/
    void printPaths(Node node) 
    {
        int path[] = new int[1000];
        printPathsRecur(node, path, 0);
    }
    
    /* Recursive helper function -- given a node, and an array containing
       the path from the root node up to but not including this node,
       print out all the root-leaf paths. */
    void printPathsRecur(Node node, int path[], int pathLen) 
    {
        if (node == null)
            return;
    
        /* append this node to the path array */
        path[pathLen] = node.data;
        pathLen++;
    
        /* it's a leaf, so print the path that led to here */
        if (node.left == null && node.right == null)
            printArray(path, pathLen);
        else
            { 
            /* otherwise try both subtrees */
            printPathsRecur(node.left, path, pathLen);
            printPathsRecur(node.right, path, pathLen);
        }
    }
    
    /* Utility that prints out an array on a line */
    void printArray(int ints[], int len) 
    {
        int i;
        for (i = 0; i < len; i++) 
            System.out.print(ints[i] + " ");
        System.out.println("");
    }
    

提交回复
热议问题