python实现二叉树的创建和遍历

简介: python实现二叉树的创建和遍历
#coding:utf-8
#author:Elvis
class TreeNode(object):
    def __init__(self):
        self.data = '#'
        self.l_child = None
        self.r_child = None
class Tree(TreeNode):
    #create a tree
    def create_tree(self, tree):
        data = raw_input('->')
        if data == '#':
            tree = None
        else:
            tree.data = data
            tree.l_child = TreeNode()
            self.create_tree(tree.l_child)
            tree.r_child = TreeNode()
            self.create_tree(tree.r_child)
    #visit a tree node
    def visit(self, tree):
        #输入#号代表空树
        if tree.data is not '#':
            print str(tree.data) + '\t',
    #先序遍历
    def pre_order(self, tree):
        if tree is not None:
            self.visit(tree)
            self.pre_order(tree.l_child)
            self.pre_order(tree.r_child)
    #中序遍历
    def in_order(self, tree):
        if tree is not None:
            self.in_order(tree.l_child)
            self.visit(tree)
            self.in_order(tree.r_child)
    #后序遍历
    def post_order(self, tree):
        if tree is not None:
            self.post_order(tree.l_child)
            self.post_order(tree.r_child)
            self.visit(tree)
t = TreeNode()
tree = Tree()
tree.create_tree(t)
tree.pre_order(t)
print '\n'
tree.in_order(t)
print '\n'
tree.post_order(t)
相关文章
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III
本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。
41 6
|
1月前
|
Python
【Leetcode刷题Python】114. 二叉树展开为链表
LeetCode上114号问题"二叉树展开为链表"的Python实现,通过先序遍历二叉树并调整节点的左右指针,将二叉树转换为先序遍历顺序的单链表。
21 3
【Leetcode刷题Python】114. 二叉树展开为链表
|
1月前
|
索引 Python
【Leetcode刷题Python】从列表list中创建一颗二叉树
本文介绍了如何使用Python递归函数从列表中创建二叉树,其中每个节点的左右子节点索引分别是当前节点索引的2倍加1和2倍加2。
36 7
|
18天前
|
存储 消息中间件 大数据
Python里for循环要遍历的数据很多很大怎么办?
遇到大数据量问题时,重要的是确定最优解决方案,这取决于数据的来源、性质以及所需的处理方式。分析数据传输、存储与处理的瓶颈是提升性能的关键。通过结合上述的技巧和方法,可以在内存和性能方面找到合适的平衡点来处理大规模数据集。
32 0
|
1月前
|
存储 算法 Python
【Leetcode刷题Python】297. 二叉树的序列化与反序列化
LeetCode第297题"二叉树的序列化与反序列化"的Python语言解决方案,包括序列化二叉树为字符串和反序列化字符串为二叉树的算法实现。
20 5
|
1月前
|
Python
【Leetcode刷题Python】236. 二叉树的最近公共祖先
LeetCode上236号问题"二叉树的最近公共祖先"的Python实现,使用递归方法找到两个指定节点的最近公共祖先。
28 5
|
1月前
|
算法 Python
【Leetcode刷题Python】剑指 Offer 33. 二叉搜索树的后序遍历序列
本文提供了一种Python算法,用以判断给定整数数组是否为某二叉搜索树的后序遍历结果,通过识别根节点并递归验证左右子树的值是否满足二叉搜索树的性质。
15 3
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - II. 从上到下打印二叉树 II
本文提供了一种Python实现方法,用于层次遍历二叉树并按层打印结果,每层节点按从左到右的顺序排列,每层打印到一行。
28 3
|
1月前
|
Python
【Leetcode刷题Python】199. 二叉树的右视图
LeetCode上199号问题"二叉树的右视图"的Python实现,通过深度优先搜索算法按层序从右向左访问节点,以获取每层的最右边节点的值。
20 4
|
1月前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - I. 从上到下打印二叉树
本文介绍了使用Python实现从上到下打印二叉树的解决方案,采用层次遍历的方法,利用队列进行节点的访问。
29 2