mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-23 08:51:31 -04:00
Create bst_convert_sorted_array.py
This commit is contained in:
parent
072febeb9c
commit
eb7a7af574
1 changed files with 25 additions and 0 deletions
25
trees/bst_convert_sorted_array.py
Normal file
25
trees/bst_convert_sorted_array.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
# note that there is no unique solution, and different choices
|
||||
# for the root node would reflect on p is defined
|
||||
|
||||
|
||||
def convert_sorted_array_bst(nums):
|
||||
|
||||
def helper(left, right):
|
||||
|
||||
if left > right:
|
||||
return None
|
||||
|
||||
p = (left + right) // 2
|
||||
|
||||
root = Node(nums[p])
|
||||
root.left = helper(left, p - 1)
|
||||
root.right = helper(p + 1, right)
|
||||
|
||||
return root
|
||||
|
||||
return helper(0, len(nums) - 1)
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue