Binary Tree二叉树—python实现

Binary Tree -- 二叉树

本文记录二叉树的python语言实现:
基于List和class的实现


一、基于List 实现

# 用列表实现二叉树 [[root],[left-tree],[right-tree]]

def Binary_tree(root:any) -> list:
    return [root,[],[]]

def insertLeft(root:list, newBranch:list) -> list:
    left = root.pop(1)
    if len(left) > 1: # 若原二叉树中存在左子树,插入后的左子树作为原左子树的父节点
        root.insert(1,[newBranch, left, []])
    else :
        root.insert(1,[newBranch, [], []])
    return root

def insertRight(root:list, newBranch:list) -> list:
    right = root.pop(2)
    if len(right) > 1:
        root.insert(2,[newBranch,[],right])
    else :
        root.insert(2,[newBranch,[],[]])
    return root

def getRootVal(root:list) -> any:
   return root[0]

def setRootVal(root:list, newVal:any) -> None:
   root[0] = newVal

def getLeftChild(root:list) -> any:
   return root[1]

def getRightChild(root:list) -> any:
   return root[2]

二、基于class的实现

class Binarytree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

    def insertLeft(self,newNode):
        if self.leftChild == None:
            self.leftChild = Binarytree(newNode)
        else : # 当插入前tree中存在左子树,那需让原左子树下调一层 
            left = Binarytree(newNode)
            left.leftChild = self.leftChild
            self.leftChild = left
    
    def insertRight(self,newNode):
        if self.rightChild == None:
            self.rightChild = Binarytree(newNode)
        else :
            right = Binarytree(newNode)
            right.rightChild = self.rightChild
            self.rightChild = right
    
    def getRightChild(self):
        return self.rightChild
    
    def getLeftChild(self):
        return self.leftChild
    
    def setRootVal(self,obj:any):
        self.key = obj
    
    def getRootVal(self):
        return self.key
        
    # 两种class内遍历方法还未测试
    # 前序遍历的class内实现
    def preorder(self):
        print(self.key)
        if self.leftChild() != None:
            self.leftChild.preorder()
        if self.rightChild() != None:
            self.rightChild.preorder()
    
    # 中序遍历的class内实现
    def inorder(self):
        if self.leftChild() != None:
            self.leftChild.inorder()
        print(self.key)
        if self.rightChild() != None:
            self.rightChild.inorder()
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值