zoukankan      html  css  js  c++  java
  • python3 二叉树实现

    code

    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:
                t = BinaryTree(newNode)
                t.leftChild = self.leftChild
                self.leftChild = t
    
        def insertRight(self, newNode):
            if self.rightChild == None:
                self.rightChild = BinaryTree(newNode)
            else:
                t = BinaryTree(newNode)
                t.rightChild = self.rightChild
                self.rightChild = t
    
        def getRightChild(self):
            return self.rightChild
    
        def getLeftChild(self):
            return self.leftChild
    
        def setRootVal(self, obj):
            self.key = obj
    
        def getRootVal(self):
            return self.key
    
        # 树的前序遍历
        # 树的后序遍历以及中序遍历见ParseTree.py
        def preorder(self):
            print(self.key)
            if self.leftChild:
                self.leftChild.preorder()
            if self.rightChild:
                self.rightChild.preorder()
    
    '''
    以下为测试数据, 去掉 # 即可
    '''
    r = BinaryTree('a')
    print(r.getRootVal())#a
    print(r.getLeftChild())
    r.insertLeft('b')
    print(r.getLeftChild())
    print(r.getLeftChild().getRootVal())#b
    r.insertRight('c')
    print(r.getRightChild())
    print(r.getRightChild().getRootVal())#c
    r.getRightChild().setRootVal('hello') 
    print(r.getRightChild().getRootVal())#hello
    print(r.getLeftChild().getRootVal())#b
    print("*"*10)
    print("preorder",r.preorder())

    outputs

    macname@MacdeMBP ~ % python3 test.py
    a
    None
    <__main__.BinaryTree object at 0x102c9aba8>
    b
    <__main__.BinaryTree object at 0x102c9abe0>
    c
    hello
    b
    **********
    a
    b
    hello
    preorder None
    macname@MacdeMBP ~ % 

  • 相关阅读:
    【题解】[HEOI2016/TJOI2016]字符串
    【题解】CF1037H Security
    Centos 7开机自启动oracle
    WRH$_ACTIVE_SESSION_HISTORY打补丁14084247实现自动分区
    oracle设置awr采集间隔和保留时间
    dgbroker配置Fast-Start Failover
    dgbroker删除后切换为手工管理
    删除dgbroker
    现有dgbroker管理的dg下添加一台从库且互相切换
    linux-unzip-error
  • 原文地址:https://www.cnblogs.com/sea-stream/p/13767642.html
Copyright © 2011-2022 走看看