@@ -54,6 +54,27 @@ def get_pair_with_sum(root, target):
5454 return False
5555
5656
57+ def get_pair_with_sum_rec (root , node , val ):
58+ if not node :
59+ return False
60+ orignl_root = root
61+ diff = val - node .data
62+ if has_other_pair (orignl_root , node , diff ):
63+ first_part = val - diff
64+ return first_part , diff
65+ return get_pair_with_sum_rec (orignl_root , node .left , sum ) or \
66+ get_pair_with_sum_rec (orignl_root , node .right , sum )
67+
68+
69+ def has_other_pair (root , this_node , rem ):
70+ if not root :
71+ return
72+ if root .data == rem and this_node != root :
73+ return root .data
74+ elif root .data < rem :
75+ return has_other_pair (root .right , this_node , rem )
76+ elif root .data > rem :
77+ return has_other_pair (root .left , this_node , rem )
5778
5879if __name__ == "__main__" :
5980 root = BSTNode (4 )
@@ -67,5 +88,7 @@ def get_pair_with_sum(root, target):
6788 root .right .left = BSTNode (5 )
6889 root .right .right = BSTNode (7 )
6990
70- sum = 8
71- print get_pair_with_sum (root , sum )
91+ sum = 4
92+ for sum in xrange (1 , 15 ):
93+ print get_pair_with_sum (root , sum ),
94+ print get_pair_with_sum_rec (root , root , sum )
0 commit comments