Sunday, November 4, 2012

Binary Search Tree: Any Path Sum

You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.



Input/Output:

printing inorder: 
1 3 4 5 6 7 8 9 10 12 13 15 17 
printing preorder: 
7 5 3 1 4 6 12 9 8 10 15 13 17 
printing path(s):
7 -> 5 -> null
5 -> 3 -> 4 -> null
12 -> null

1 comment:

  1. It doesn't cover paths which extend into both subtrees, e.g. for sum 8 it doesn't print 1 -> 3 -> 4 -> null.

    ReplyDelete