defpre(root): if root == None: return print(root.number) pre(root.lchild) pre(root.rchild)
defmid(root): if root == None: return mid(root.lchild) print(root.number) mid(root.rchild)
defback(root): if root == None: return back(root.lchild) back(root.rchild) print(root.number)
不用太多解释了吧,只是打印顺序的问题。
递归排序
除了上述的遍历方式,还有递归方式获取,这里先写个前序排序的递归
1 2 3 4 5 6 7 8 9
defpre_queue(root): stack = [root] whilelen(stack): p = stack.pop() print(p.number) if p.rchild: stack.append(p.rchild) if p.lchild: stack.append(p.lchild)
defpre(root): if root == None: return print(root.number) pre(root.lchild) pre(root.rchild)
defmid(root): if root == None: return mid(root.lchild) print(root.number) mid(root.rchild)
defback(root): if root == None: return back(root.lchild) back(root.rchild) print(root.number)
defpre_queue(root): stack = [root] whilelen(stack): p = stack.pop() print(p.number) if p.rchild: stack.append(p.rchild) if p.lchild: stack.append(p.lchild)
if'__main__' == __name__: t = Tree() L = [1,2,3,4,5,6,7] for x in L: t.add(x) print('sucess')