Exploring Binary Tree Paths in Python

Dynamic Tree Path Traversal

Akhil Kumar
TheCodingWay
3 min readNov 21, 2023

--

Binary trees are a fundamental data structure in computer science, widely used for representing hierarchical relationships. Traversing a binary tree and finding all possible paths from the root to the leaf nodes is a common problem. In this article, we will explore a Python solution to this problem using a depth-first search (DFS) approach.

Photo by Nathan da Silva on Unsplash

Understanding the Code

Let’s begin by examining the provided Python code, which is a part of a class named Solution that contains a method called binaryTreePaths. This method takes a root parameter, representing the root of a binary tree, and returns a list of strings representing all possible paths from the root to the leaf nodes.

The binary tree node is defined by the class TreeNode, which has a constructor initializing the node's value (val), left child (left), and right child (right).

class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

Now, let’s break down the binaryTreePaths method.

def binaryTreePaths(self, root):
if root is None:
return []
if root.left is None and root.right is None:
return [str(root.val)]
left_subtree_paths = self.binaryTreePaths(root.left)
right_subtree_paths = self.binaryTreePaths(root.right)
left_subtree_paths = [str(root.val) + "->" + path for path in left_subtree_paths]
right_subtree_paths = [str(root.val) + "->" + path for path in right_subtree_paths]
return left_subtree_paths + right_subtree_paths

Algorithm Explanation

Base Cases:

  • If the root is None, it means an empty tree, and an empty array is returned.
  • If the root is a leaf node (both left and right children are None), a single-element array containing the string representation of the leaf node's value is returned.

Recursive Calls:

  • The method recursively calls itself on the left and right subtrees to obtain the paths from the left and right children.

Path Construction:

  • Each path in the left and right subtrees is augmented by appending the current node’s value and an arrow (->) using list comprehension.

Combining Paths:

  • The paths from the left and right subtrees are concatenated, and the final result is returned.

Example Usage

Let’s illustrate the usage of this code with a simple example:

# Example tree:
# 1
# / \
# 2 3
# \
# 5
# Constructing the tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(5)
# Creating an instance of the Solution class
solution = Solution()
# Finding all binary tree paths
paths = solution.binaryTreePaths(root)
# Displaying the result
print(paths)

In this example, the expected output would be ['1->2->5', '1->3'], representing all possible paths from the root to the leaf nodes.

Conclusion

Understanding and solving problems related to binary trees is crucial for any programmer. The provided Python code efficiently explores all paths in a binary tree, demonstrating the power of recursive algorithms and depth-first search. This solution can be adapted and extended for various applications involving binary tree traversal and path finding.

--

--