码迷,mamicode.com
首页 > 编程语言 > 详细

Python实现打印二叉树某一层的所有节点

时间:2015-06-14 00:29:17      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

不多说,直接贴程序,如下所示

# -*- coding: utf-8 -*-

# 定义二叉树节点类
class TreeNode(object):
    def __init__(self,data=0,left=0,right=0):
        self.data = data
        self.left = left
        self.right = right

# 遍历某一层所有节点,并打印
def TransLevel(root,level):
    if root == None:
        return
    else:
        if level == 1 and  isinstance(root, TreeNode):
            print "%s " % root.data,
        else:
            if isinstance(root, TreeNode):
                TransLevel(root.left, level-1)
                TransLevel(root.right, level-1)



# 建立的二叉树
# ------------------------
#          root
#       7        8
#     6
#   2   5
# 1    3 4
#
# -------------------------

n1 = TreeNode(data=1)
n2 = TreeNode(2,n1,0)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5,n3,n4)
n6 = TreeNode(6,n2,n5)
n7 = TreeNode(7,n6,0)
n8 = TreeNode(8)
root = TreeNode(root,n7,n8)

TransLevel(root, 5)

参考资料:

1、python数据结构之二叉树遍历的实现
http://www.cnblogs.com/yupeng/p/3414451.html

2、打印二叉树某一层的节点
http://www.cnblogs.com/-Lei/archive/2013/02/25/2928629.html

Python实现打印二叉树某一层的所有节点

标签:

原文地址:http://www.cnblogs.com/klchang/p/4574406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!