最近Leetcode的每日一题总是会出现跟树有关的题,因此最近学习一下用Python实现二叉树。
首先,我们可以使用嵌套列表来表示二叉树,形式如下。
[Root,Left,Right]
![]()
下面我们介绍一些函数来介绍:
第一个函数,创建二叉树:
- 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 getRootVal(root): # 得到根结点的值
- return root[0]
-
-
- def setRootVal(root, newVal): # 重置根结点的值
- root[0] = newVal
-
-
- def getLeftChild(root): # 得到左子树
- return root[1]
-
-
- def getRightChild(root): # 得到右子树
- return root[2]
其次,我们可以使用链表来表示二叉树。
下面,我们看一下代码(功能在注释中) 。
- 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