forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_326.py
35 lines (25 loc) · 783 Bytes
/
problem_326.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
from typing import List
class Node:
def __init__(self, val: int):
self.val = val
self.l = None
self.r = None
def __repr__(self):
return "{}=[l->{}, r->{}]".format(self.val, self.l, self.r)
def make_cartree(arr: List[int], last: Node, root: Node):
if not arr:
return root
node = Node(arr[0])
if not last:
return make_cartree(arr[1:], node, node)
if last.val > node.val:
node.l = last
return make_cartree(arr[1:], node, node)
last.r = node
return make_cartree(arr[1:], last, last)
# Tests
cartree = make_cartree([3, 2, 6, 1, 9], None, None)
assert str(cartree) == \
"1=[l->2=[l->3=[l->None, r->None], " + \
"r->6=[l->None, r->None]], " + \
"r->9=[l->None, r->None]]"