zoukankan      html  css  js  c++  java
  • python 树

    class Node:
        """
        节点类
        """
        def __init__(self, value=None, left=None, right=None):
            self.val = value
            self.left = left
            self.right = right
    
    class Tree:
        """
        树类
        """
        def __init__(self):
            self.root = Node()
            self.queue = []
    
        def add(self, val):
            """
            为树添加节点
            """
            node = Node(value=val)
    
            if self.root.val is None:  # 如果树是空的,则当前节点为根节点
                self.root = node
                self.queue.append(self.root)
            else:
                treeNode = self.queue[0]
                if treeNode.left is None:
                    treeNode.left = node
                    self.queue.append(treeNode.left)
                else:
                    treeNode.right = node
                    self.queue.append(treeNode.right)
                    self.queue.pop(0)  # 如果该节点存在左右子树,将此节点丢弃
    
        def pre_order(self,node):       # 先序遍历:根左右
            print(node.val)
            if node.left is not None:
                self.pre_order(node.left)
            if node.right is not None:
                self.pre_order(node.right)
                
        def center_order(self,node): # 中序遍历:左根右
            if node.left is not None:
                self.center_order(node.left)
            print(node.val)
            if node.right is not None:
                self.center_order(node.right)
        
        def post_order(self,node): # 后序遍历:左右根
            if node.left is not None:
                self.post_order(node.left)
            if node.right is not None:
                self.post_order(node.right)
            print(node.val)
    
    
    if __name__ == '__main__':
        tree = Tree()  # 新建一个树对象
        for val in range(10):
            tree.add(val)
    
        tree.post_order(tree.root)
    
  • 相关阅读:
    关于token的理解
    JavaScript 中 call()、apply()、bind() 的用法
    常用JS整理
    js里面for循环的++i与i++
    前端命名规范
    H5混合开发app常用代码
    jquery知识巩固
    水平垂直居中(固定宽不固定宽)
    css3新属性运用
    bug笔记(pc)
  • 原文地址:https://www.cnblogs.com/wztshine/p/13687832.html
Copyright © 2011-2022 走看看