print all root to leaf paths in a binary tree

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

    You can do the following,

    public static void printTreePaths(Node node) {
        int treeHeight = treeHeight(node);
        int[] path = new int[treeHeight];
        printTreePathsRec(node, path, 0);
    
    }
    
    private static void printTreePathsRec(Node node, int[] path, int pathSize) {
        if (node == null) {
            return;
        }
    
        path[pathSize++] = node.data;
    
        if (node.left == null & node.right == null) {
            for (int j = 0; j < pathSize; j++ ) {
                System.out.print(path[j] + " ");
            }
            System.out.println();
        }
    
         printTreePathsRec(node.left, path, pathSize);
         printTreePathsRec(node.right, path, pathSize);
    }
    

    public static int treeHeight(Node root) {
        if (root == null) {
            return 0;
        }
    
        if (root.left != null) {
            treeHeight(root.left);
        }
    
        if (root.right != null) {
            treeHeight(root.right);
        }
    
        return Math.max(treeHeight(root.left), treeHeight(root.right)) + 1;
    
    }
    

提交回复
热议问题