Python 建立二叉树
Python 建立二叉树
在做《剑指Offer》的时候总是弄不清楚二叉树的概念,现在学习了如何创建二叉树,希望有所帮助。
按照下图中二叉树来写
首先定义初始化函数:
class TreeNode:
def __init__(self, val, left=None, right=None):
self.data = val
self.left = left
self.right = right
这是对树的根左右结点进行定义。例如A-B-C
那么:
B = TreeNode('b')
C = TreeNode('c')
A = TreeNode('a', B, C)
#A = TreeNode('a', None, C) 表示没有左结点
或者
B = TreeNode('b')
C = TreeNode('c')
A = TreeNode('a')
A.left = B
A.right = C
对图中的二叉树进行定义
A, B, C, D, E, F, G, H, I, J, K, L ,M ,N = [TreeNode(x) for x in 'abcdefghijklmn']
A.left = B
A.right = C
B.left = D
B.right = E
C.left = F
C.right = G
D.left = H
E.left = I
E.right = J
F.right = K
G.left = L
G.right = M
M.right = N
print G.data
g
print G.left.data
l