主要是:前序遍历、中序遍历、后序遍历、层级遍历、非递归前序遍历、非递归中序遍历、非递归后序遍历
代码如下:
#!/usr/bin/env python
#-*- coding:utf8 -*-
class TreeNode(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class Tree(object):
def __init__(self, root=None):
self.root = None
def makeTree(self, data, left, right):
self.root = TreeNode(data, left, right)
def is_empty(self):
"""是否为空 """
if self.root is None:
return True
return False
def preOrder(self, r):
"""前序遍历 """
if not r.is_empty():
print r.root.data
if r.root.left is not None:
r.preOrder(r.root.left)
if r.root.right is not None:
r.preOrder(r.root.right)
def inOrder(self, r):
"""中序遍历 """
if not r.is_empty():
if r.root.left is not None:
r.preOrder(r.root.left)
print r.root.data
if r.root.right is not None:
r.preOrder(r.root.right)
def postOrder(self, r):
"""后续遍历 """
if not r.is_empty():
if r.root.left is not None:
r.preOrder(r.root.left)
print r.root.data
if r.root.right is not None:
新闻热点
疑难解答