zoukankan      html  css  js  c++  java
  • 二叉树(python实现)

    二叉树的遍历和添加结点

    class Node():
        def __init__(self, item):
            self.elem = item
            self.l_child = None
            self.r_child = None
    
    class Tree():
        def __init__(self):
            self.root = None
    
        def add(self, elem):
            """为树添加节点"""
            node = Node(elem)
            # 如果树是空的,则对根节点赋值
            if self.root is None:
                self.root = node
                return
            else:
                queue = []
                queue.append(self.root)
                # 对已有节点进行层次遍历
                while queue:
                    # 弹出队列的第一个元素
                    cur = queue.pop(0)
                    if cur.l_child == None:
                        cur.l_child = node
                        return
                    elif cur.r_child == None:
                        cur.r_child = node
                        return
                    else:
                        # 如果左右子树都不为空,加入队列继续判断
                        queue.append(cur.l_child)
                        queue.append(cur.r_child)
    
        def preorder(self, root):
            if root == None:
                return
            print(root.elem, end='')
            self.preorder(root.lchild)
            self.preorder(root.rchild)
    
            def inorder(self, root):
                """递归实现中序遍历"""
                if root == None:
                    return
                self.inorder(root.lchild)
                print(root.elem, end=" ")
                self.inorder(root.rchild)
    
            def postorder(self, root):
                """递归实现后续遍历"""
                if root == None:
                    return
                self.postorder(root.lchild)
                self.postorder(root.rchild)
                print(root.elem, end=" ")
    
            # ××××××××××    广度优先遍历   ×××××××××
            # 从树的root开始,从上到下从从左到右遍历整个树的节点
            def breadth_travel(self):
                """利用队列实现树的层次遍历"""
                if self.root == None:
                    return
                queue = [self.root]
                while queue:
                    node = queue.pop(0)
                    print(node.elem, end=" ")
                    if node.lchild != None:
                        queue.append(node.lchild)
                    if node.rchild != None:
                        queue.append(node.rchild)
  • 相关阅读:
    python 匿名函数lambda()
    python列表推导式
    python数组的基本操作一(添加,扩展,插入)
    Python的数字类型
    Python初识以及Windows安装教程
    字典简单使用
    two sum(LeetCode)
    python读写文件
    C++ volatile关键字(转)
    实验一
  • 原文地址:https://www.cnblogs.com/sometingintheway/p/11961464.html
Copyright © 2011-2022 走看看