-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_test.py
60 lines (48 loc) · 1.22 KB
/
local_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#传入链表头节点,以数组形式返回
def print_linked_list(head):
cur = head
res = []
while cur:
res.append(cur.val)
cur = cur.next
return res
# 打印树
def print_bst(root):
def recursion(res,root):
if not root: res.append(None)
res.append(root.val)
if root.left:
recursion(res,root.left)
if root.right:
recursion(res,root.right)
res = []
recursion( res,root)
return res
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#定义节点
class ListNode():
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getBSTree(self, nums):
if not nums:
return None
mid = len(nums)//2
root = TreeNode(nums[mid])
left = nums[:mid]
right = nums[mid+1:]
root.left = self.getBSTree(left)
root.right = self.getBSTree(right)
return root
if __name__ == "__main__":
solution = Solution()
nums = [-10,-3,0,5,9]
root = solution.getBSTree(nums)
res = print_bst(root)
print(res)