Skip to content

Instantly share code, notes, and snippets.

@addie
Last active January 24, 2016 16:17
Show Gist options
  • Save addie/fe606d67dae2b35bd4ff to your computer and use it in GitHub Desktop.
Save addie/fe606d67dae2b35bd4ff to your computer and use it in GitHub Desktop.
Recursively prints every path from root to leaf in a binary search tree that meets a given condition
# coding: utf-8
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
def paths(root, k):
_paths(root, k, [], 0)
def _paths(root, k, s, count):
if not root:
return
s.append(root.value)
count += root.value
if not root.left and not root.right:
print_selected_path(k, s, count)
else:
_paths(root.left, k, s, count)
_paths(root.right, k, s, count)
s.pop()
def print_selected_path(k, s, count):
if count < k:
print s
tree1 = Node(35)
tree1.left = Node(28)
tree1.left.left = Node(2)
tree1.left.left.left = Node(1)
tree1.left.right = Node(29)
tree1.right = Node(45)
tree1.right.left = Node(41)
tree1.right.left.right = Node(43)
tree1.right.right = Node(55)
paths(tree1, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment