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

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

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

    定义二叉树2

    代码如下:

    #定义二叉树

    def BinaryTree(r):

        return [r,[],[]]

    def insertLeft(root,newBranch): #添加做子节点

        t = root.pop(1)

        if len(t) > 1:

            root.insert(1,[newBranch,t,[]])

        else:

            root.insert(1,[newBranch,[],[]])

        return root

    def insertRight(root,newBranch):#添加右子节点

        t = root.pop(2)

        if len(t) > 1:

            root.insert(2,[newBranch,[],t])

        else:

            root.insert(2,[newBranch,[],[]])

        return root

    def getRootVal(root): #获取根值

        return root[0]

    def setRootVal(root,newVal): #设置根值

        root[0] = newVal

    def getLeftChild(root): #获取左子树

        return root[1]

    def getRightChild(root): #获取右子树

        return root[2]

    r = BinaryTree(3)

    insertLeft(r,4)

    insertLeft(r,5)

    insertRight(r,6)

    insertRight(r,7)

    l = getLeftChild(r)

    #print(l)

    #r = getRightChild(r)

    #print(r)

    setRootVal(l,9)

    print(r)

    insertLeft(l,11)

    print(r)

    print(getRightChild(getRightChild(r)))

    运行结果为:

    [3, [9, [4, [], []], []], [7, [], [6, [], []]]]

    [3, [9, [11, [4, [], []], []], []], [7, [], [6, [], []]]]

    [6, [], []]

    相关文章

      网友评论

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

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