Skip to content

Commit

Permalink
32.py
Browse files Browse the repository at this point in the history
  • Loading branch information
huisuu committed Aug 21, 2024
1 parent 8c2f13d commit e268542
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions HSKIM/31to40/32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from collections import deque


class Node:
def __init__(self, info, num, left=None, right=None):
self.info = info
self.left = left
self.right = right
self.num = num

def has_left(self):
return self.left is not None

def has_right(self):
return self.right is not None

def build_binary_tree(nodeinfo):
nodes = [i for i in range(1, len(nodeinfo) + 1)]
nodes.sort(key=lambda x: (nodeinfo[x-1][1], -nodeinfo[x-1][0]), reverse=True)
root = None

for i in range(len(nodes)):
if root is None:
root = Node(nodeinfo[nodes[0] - 1], nodes[0])
else:
parent = root
node = Node(nodeinfo[nodes[i] - 1], nodes[i])

while True:
if node.info[0] < parent.info[0]:
if parent.has_left():
parent = parent.left
continue
parent.left = node
break
else:
if parent.has_right():
parent = parent.right
continue
parent.right = node
break
return root

def pre_order(root, answer):
stack = [root]
while stack:
node = stack.pop()
if node is None:
continue
answer[0].append(node.num)
stack.append(node.right)
stack.append(node.left)

def post_order(root, answer):
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if node is None:
continue
if visited:
answer[1].append(node.num)
else:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))

def solution(nodeinfo):
answer = [[], []]
root = build_binary_tree(nodeinfo)
pre_order(root, answer)
post_order(root, answer)
return answer

nodeinfo = [[5, 3], [11, 5], [13, 3], [3, 5], [6,1], [1, 3], [8, 6], [7, 2],
[2, 2]]
print(solution(nodeinfo))

0 comments on commit e268542

Please sign in to comment.