Binary Tree Paths

Problem Statement

deeksha sharma
Algorithm Problems
1 min readJan 19, 2016

--

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

For example, given the following binary tree:

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

Approach

  • If the root is null, return empty list
  • If root.left and root.right are null, then return root in a String
  • If root.left is null then recursively traverse path of the right subtree until the leaf
  • If root.right is null then recursively traverse path of the left subtree until the leaf
  • If root.left and root.right both are not null
  • Recursively traverse the left and right subtrees
  • One thing to notice is since we are creating the paths using a String. Each recursive call requires a new String concatenated with the existing path already discovered.

Run Time Complexity

The time complexity for this problem is O(n). In the worst case we shall be visiting all the nodes of the tree.

Code

--

--

deeksha sharma
Algorithm Problems

Work for https://bonsaiilabs.com/ life long learner ,investing time heavily in personal finance, education, tech and design skills. Twitter: @deekshasharma25