数据结构-树
树的概念
用树结构实现简单文件系统
class Node: def __init__(self, name, type="dir"): self.name = name self.type = type # dir or file self.children = [] self.parent = None def __repr__(self): return self.name class FileSystemTree: def __init__(self): self.root = Node('/') self.now = self.root def mkdir(self, name): # name 以/结尾 if name[-1] != "/": name += '/' node = Node(name) self.now.children.append(node) node.parent = self.now def ls(self): return self.now.children def cd(self, name): # 只支持相对路径 if name[-1] != "/": name += '/' for child in self.now.children: if child.name == name: self.now = child return raise ValueError("invalid dir") tree = FileSystemTree() tree.mkdir("var/") tree.mkdir("bin/") tree.mkdir("usr") print(tree.root.children) tree.cd("bin/") tree.mkdir("python/") print(tree.ls())
二叉树
二叉树的链式存储:将二叉树的节点定义为一个对象,节点之间通过类似链表的链接方式来链接
class BiTreeNode: def __init__(self, data): self.data = data self.lchild = None self.rchild = None
二叉树遍历
一般有了中序和前序序列就能确定这颗树长啥样,由前序确定根节点,中序确定左右子树
from collections import deque class BiTreeNode: def __init__(self, data): self.data = data self.lchild = None self.rchild = None a = BiTreeNode("A") b = BiTreeNode("B") c = BiTreeNode("C") d = BiTreeNode("D") e = BiTreeNode("E") f = BiTreeNode("F") g = BiTreeNode("G") e.lchild = a e.rchild = g a.rchild = c c.lchild = b c.rchild = d g.rchild = f root = e # 前序遍历 def pre_order(root): if root: print(root.data, end=',') pre_order(root.lchild) pre_order(root.rchild) # 中序遍历 def in_order(root): if root: in_order(root.lchild) print(root.data, end=',') in_order(root.rchild) # 后序遍历 def post_order(root): if root: post_order(root.lchild) post_order(root.rchild) print(root.data, end=',') # 层级遍历 def level_order(root): queue = deque() queue.append(root) while len(queue) > 0: node = queue.popleft() print(node.data, end=',') if node.lchild: queue.append(node.lchild) if node.rchild: queue.append(node.rchild) # pre_order(root) # in_order(root) # post_order(root) level_order(root)