问题
如何遍历一个二叉树
遍历二叉树就是访问二叉树的每一个节点
二叉树父结点下先左访问,先序遍历(根左右)
例如:遍历以下的二叉树
遍历结果:ABDECF
Python代码示例
# !/usr/bin/env python
# -*-encoding: utf-8-*-
# author:LiYanwei
# version:0.1
class TreeNode(object):
'''
二叉树类
'''
def __init__ (self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def createTree():
'''
创建二叉树函数
'''
# 创建如图的二叉树
# 1.创建节点
A = TreeNode('A')
B = TreeNode('B')
C = TreeNode('C')
D = TreeNode('D')
E = TreeNode('E')
F = TreeNode('F')
# 列表解析
# A, B, C, D, E, F = [TreeNode(x) for x in 'ABCDEF']
# 2.创建节点之间的关系
A.left = B
A.right = C
B.left = D
B.right = E
C.left = F
return A
def preOrder(node):
'''
先序遍历 先左后右 使用递归
:param node:
:return:
'''
if node is None:
return
print node.data
preOrder(node.left)
preOrder(node.right)
if __name__ == '__main__':
# 二叉树的创建
root = createTree()
# 二叉树的遍历
preOrder(root)