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

2021-02-04  本文已影响0人  Alyna_C

定义二叉树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, [], []]

上一篇下一篇

猜你喜欢

热点阅读