Friday, October 30, 2020

Given a binary tree, return all root-to-leaf paths.

Example:

Input:

   1
 /   \
2     3
 \
  4

Output: ["1->2->4", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->4, 1->3


Approach: Using Pre-Order traversal. Approach is easy to understand even by just looking at the code.


Implementation in C#:

        public IList<string> RootToLeafPaths()

        {

            List<string> result = new List<string>();

            if (this.Root == null)

            {

                return result;

            }

            string currPath = string.Empty;

            this.RootToLeafPaths(this.Root, currPath, ref result);

            return result;

        }


        private void RootToLeafPaths(BinaryTreeNode node, string currPath, ref List<string> result)

        {

            if (string.IsNullOrWhiteSpace(currPath))

            {

                currPath = $"{node.Value}";

            }

            else

            {

                currPath += $"->{node.Value}";

            }

            // Get the leaf node, Add current path to result

            if (node.LeftNode == null && node.RightNode == null)

            {

                result.Add(currPath);

                return;

            }

            if (node.LeftNode != null)

            {

                this.RootToLeafPaths(node.LeftNode, currPath, ref result);

            }

            if (node.RightNode != null)

            {

                this.RootToLeafPaths(node.RightNode, currPath, ref result);

            }

        }


Complexity: O(n)

No comments:

Post a Comment