Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers.
# Example:
# * construct([3,2,5,7,1],T).
# T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil)))
# Then use this predicate to test the solution of the problem P56.
# Example:
# * test-symmetric([5,3,18,1,4,12,21]).
# Yes
# * test-symmetric([3,2,5,7,1]).
# No
def construct(nums):
if not nums:
return None
ordered_nums = sorted(nums)
center_index = (len(nums) / 2)
return (ordered_nums[center_index], construct(ordered_nums[:center_index]), construct(ordered_nums[center_index+1:]))
def test_symmetric(nums):
return symmetric_binary_tree(construct(nums))
No comments:
Post a Comment