赞
踩
在构建之前需要先定义二叉树节点:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
需要注意给 val、left 以及 right 赋予默认值。此时调用 TreeNode() 返回的是一个值为 0 的根节点,需要连接这些孤立的节点形成二叉树。
初始化树节点的值:
node1 = TreeNode(5)
node2 = TreeNode(3)
node3 = TreeNode(7)
node4 = TreeNode(1)
node5 = TreeNode(4)
node6 = TreeNode(6)
node7 = TreeNode(9)
初始化之后,这些节点的值不在是默认的 0,但它们还是孤立的节点,因而还需要将其连接。
连接树节点,并定义根节点 root:
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
root = node1
至此,我们就完成了使用 python 对二叉树的构建:
此外,还可以先创建叶节点,再创建连接二者的父节点:
node6 = TreeNode(6)
node7 = TreeNode(9)
node3 = TreeNode(7, node6, node7)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
node4 = TreeNode(1)
node5 = TreeNode(4)
node6 = TreeNode(6)
node7 = TreeNode(9)
node2 = TreeNode(3, node4, node5)
node3 = TreeNode(7, node6, node7)
node1 = TreeNode(5, node2, node3)
root = node1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。