美文网首页
【基础】练习册37-Python3_定义二叉树1

【基础】练习册37-Python3_定义二叉树1

作者: Alyna_C | 来源:发表于2021-02-03 06:55 被阅读0次

定义二叉树1:

代码如下:

class BinaryTree:

    def __init__(self,nodeObj): #初始化

        self.key = nodeObj

        self.leftChild = None

        self.rightChild = None

    def insertLeft(self,newNode): #插入左子树

        if not self.leftChild:

            self.leftChild = BinaryTree(newNode)

        else:

            BinaryTree(newNode).leftChild = self.leftChild

            self.leftChild = BinaryTree(newNode)

    def inserRight(self,newNode): #插入右子树

        if not self.rightChild:

            self.rightChild = BinaryTree(newNode)

        else:

            BinaryTree(newNode).rightChild = self.rightChild

            self.rightChild = BinaryTree(newNode)

    def getLeftChild(self):

        return self.leftChild

    def getRightChild(self):

        return self.rightChild

    def getRootVal(self):

        return self.key

    def setRootVal(self,obj):

        self.key = obj

r = BinaryTree('a')

print(r.getRightChild)

print(r.getLeftChild)

r.insertLeft('b')

print(r.getLeftChild()) #获得左子树地址

print(r.getLeftChild().getRootVal()) #获得左子树的值

r.inserRight('c')

print(r.getRightChild()) #获得右子树地址

print(r.getRightChild().getRootVal()) #获得右子树值

r.getRightChild().setRootVal('hello')

print(r.getRightChild().getRootVal())


运行结果为:

False

7

192:A_Primary cherish$ /usr/local/bin/python3.7 "/Users/cherish/Documents/学习3_Python/A_Primary/Arithmetic/Binary 2.py"

<bound method BinaryTree.getRightChild of <__main__.BinaryTree object at 0x101fad470>>

<bound method BinaryTree.getLeftChild of <__main__.BinaryTree object at 0x101fad470>>

<__main__.BinaryTree object at 0x101ebcf98>

b

<__main__.BinaryTree object at 0x101fad4a8>

c

hello

相关文章

  • 【基础】练习册37-Python3_定义二叉树1

    定义二叉树1: 代码如下: class BinaryTree: def __init__(self,nodeOb...

  • 满二叉树(Full Binary Tree)

    国内教程和国外对满二叉树的定义有一些的区别。 一、国内满二叉树 1、定义 2、特点 二、国外满二叉树 1、定义 2、特点

  • 二叉树的遍历

    关于二叉树的算法问题,一般都以二叉树的遍历为基础,这里给出二叉树的多种遍历方式 树结构: 树结点的定义及其构建: ...

  • 数据结构 - 二叉树(Binary Tree)

    1、二叉树定义和特点 1.1、定义 1.2、特点 2、二叉树的遍历 从根节点出发,按照某种次序依次访问二叉树中所有...

  • 【基础】练习册38-Python3_定义二叉树2

    定义二叉树2 代码如下: #定义二叉树def BinaryTree(r): return [r,[],[]]de...

  • 经典算法代码集

    本文是经典算法的集合,使用C#语言来实现。 1. 二叉树 二叉树结构定义 1.1 二叉树的遍历 先定义一个遍历处理...

  • LeetCode基础算法-树

    LeetCode基础算法-树 LeetCode 树 基础算法 1. 二叉树的最大深度 给定一个二叉树,找出其最大深...

  • 二叉树深度求导golang实现

    二叉树定义 节点值这里定义为int类型 求二叉树的深度 后续遍历方式: 二叉树结构如下: 二叉树初始化 定义求导函...

  • 面试3(计算机基础)

    按照二叉树的定义,4个节点的二叉树有多少种? 0个节点的二叉树有1种,即f(0)=1;1个节点的二叉树有1种,即f...

  • 平衡二叉树

    1.平衡二叉树定义及实现原理 平衡二叉树(Height-Balanced Binary Search Tree):...

网友评论

      本文标题:【基础】练习册37-Python3_定义二叉树1

      本文链接:https://www.haomeiwen.com/subject/owistltx.html