How to print out all path from root to leaf of a given binary tree


This is a continuation of my post How to create a binary tree in c#.In this post, I will show you how to print all path from root to leaf of a given binary tree in c#. Let’s consider following binary tree.

4

2 5

1 3

For the above tree, there are three paths from the root to leaf

Path 1 : 4 2 1

Path 2 : 4 2 3

Path 3 : 4 5

public void PrintPath()
        {
            int[] path = new int[100];
            printPaths(_root, path, 0);
        }
        private void printPaths(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 
                printPaths(node.Left, path, pathLen);
                printPaths(node.Right, path, pathLen);
            }
        }

        private void PrintArray(int[] path, int pathLen)
        {
            for (int i = 0; i < pathLen; i++)
            {
                Console.Write(path[i] + " ");
            }
            Console.WriteLine();
        }

Happy Coding 😊


Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم