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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
|
class Stack: def __init__(self): self.container=list()
def empty(self): if not self.container: return True else: return False
def push(self, data): self.container.append(data)
def pop(self): return self.container.pop()
def peek(self): return self.container[-1]
from queue import Queue
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None
def preorder(node): if not node: return print(node.data, end=" ") preorder(node.left) preorder(node.right)
def inorder(node): if not node: return
inorder(node.left) print(node.data, end=" ") inorder(node.right)
def postorder(node): if not node: return
postorder(node.left) postorder(node.right) print(node.data, end=" ")
def iter_preorder(cur): s = Stack()
while True: while cur: print(cur.data, end=" ") s.push(cur) cur = cur.left if s.empty(): break cur = s.pop() cur = cur.right
def iter_inorder(cur): s = Stack()
while True: while cur: s.push(cur) cur = cur.left if s.empty(): break cur = s.pop() print(cur.data, end=" ") cur = cur.right
def iter_postorder(cur): s1 = Stack() s2 = Stack()
s1.push(cur) while not s1.empty(): cur = s1.pop() if cur.left: s1.push(cur.left) if cur.right: s1.push(cur.right) s2.push(cur)
while not s2.empty(): cur = s2.pop() print(cur.data, end=" ")
def levelorder(cur): q = Queue() q.put(cur) while not q.empty(): cur = q.get() print(cur.data, end=" ") if cur.left: q.put(cur.left) if cur.right: q.put(cur.right)
if __name__ == "__main__": n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7)
n1.left = n2 n1.right = n3 n2.left = n4 n2.right = n5 n3.left = n6 n3.right = n7
print("전위순회 - 재귀함수") preorder(n1) print() print("중위순회 - 재귀함수") inorder(n1) print() print("후위순회 - 재귀함수") postorder(n1) print() print("--------------------") print("전위순회 - while문") iter_preorder(n1) print() print("중위순회 - while문") iter_inorder(n1) print() print("후위순회 - while문") iter_postorder(n1) print() print("레벨순회 - while문") levelorder(n1) print()
|