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
|
from squeue import *
""" 二叉树的简单实践 思路: 1.使用链式存储, 一个Node表示一个结点 2.结点使用两个属性变量表示树的左右子树,即左连接和右连接 """
class Node: def __init__(self,val,right = None,left = None): self.val = val self.right = right self.left = left
class Bitree: def __init__(self,root = None): self.root = root
def preorder(self,node): if node is None: return print(node.val,end="") self.preorder(node.left) self.preorder(node.right)
def inorder(self,node): if node is None: return self.inorder(node.left) print(node.val,end="") self.inorder(node.right)
def postorder(self,node): if node is None: return self.postorder(node.left) self.postorder(node.right) print(node.val,end = "")
def levelorder(self,node): sq = Squeue() sq.enqueue(node) while not sq.is_empty(): ndoe = sq.dequeue() print(node.val,end = "") if node.left: sq.dequeue(node.left) if node.right: sq.dequeue(node.right)
if __name__ == '__main__': b = Node('B') f = Node('F') g = Node('G') d = Node('D',f,g) i = Node('I') h = Node('H') e = Node('E',i,h) c = Node('C',d,e) a = Node('A',b,c)
bt = Bitree(a) bt.preorder(bt.root) print() bt.inorder(bt.root) print() bt.postorder(bt.root)
|