-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |