前序遍历:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
X = []
def qianxu(pHead):
if pHead == None:
return None
# 先于左子树定义和右子树递归
X.append(pHead.val)
qianxu(pHead.left)
qianxu(pHead.right)
a1 = TreeNode(10)
a2 = TreeNode(5)
a3 = TreeNode(12)
a4 = TreeNode(4)
a5 = TreeNode(7)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
qianxu(a1)
print X
中序遍历:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
X = []
def qianxu(pHead):
if pHead == None:
return None
qianxu(pHead.left)
# 后于左子树递归,先于右子树递归
X.append(pHead.val)
qianxu(pHead.right)
a1 = TreeNode(10)
a2 = TreeNode(5)
a3 = TreeNode(12)
a4 = TreeNode(4)
a5 = TreeNode(7)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
qianxu(a1)
print X
后序遍历:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def houxu(self,pRoot):
if pRoot == None:
return None
self.houxu(pRoot.left)
# 后于左子树递归,右子树递归前判断
if pRoot.right != None:
self.houxu(pRoot.right)
print pRoot.val
else:
print pRoot.val
S = Solution()
a1 = TreeNode(10)
a2 = TreeNode(5)
a3 = TreeNode(12)
a4 = TreeNode(4)
a5 = TreeNode(7)
a1.left = a2
a1.right = a3
a2.left = a4
a2.right = a5
S.houxu(a1)