例如我想创建如下的二叉树,该怎么办呢?
所幸的是Python中提供了像c语言里面的结构一样的东西,那么这个二叉树的结构就可以用类来实现,首先创建一个类:
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
鉴于此例中节点较少,可以考虑使用手动输入的方式来构造这颗树,即如下:
ne = Node('e')
nf = Node('f')
ng = Node('g')
nd = Node('d'); nd.right = ne
nb = Node('b'); nb.left = nd; nb.right = nf
nc = Node('c'); nc.right = ng
root = Node('a'); root.left = nb; root.right = nc
树构造好之后,当然就要来到三种遍历方式了:
- 前序
- 中序
- 后序
1. 前序遍历的要点是先根再左后右,而且对每个节点都是如此,这个遍历的方式可以使用递归来实现,如下
def qianxu(root):
if not root: return
print(root.val, end=' ')
qianxu(root.left)
qianxu(root.right)
qianxu(root)
输出结果为不出所料。
2. 中序
def zhongxu(root):
if not root: return
zhongxu(root.left)
print(root.val, end=' ')
zhongxu(root.right)
zhongxu(root)
3. 后序
def houxu(root):
if not root: return
houxu(root.left)
houxu(root.right)
print(root.val, end=' ')
houxu(root)
看到这里,不得不佩服递归的强大。
还有一个好玩的就是怎么找路径的问题,这里可以借鉴前序遍历,比如说找节点 f 的路径,可以怎么玩呢?看看如下的方法:
path = []
def findPath(root, char):
if not root: return
path.append(root.val)
if root.val==char:
print(' '.join(path))
findPath(root.left, char)
findPath(root.right, char)
findPath(root, 'f')
这段代码的输出结果为 a b d e f,差不多就是前序遍历(a b d e f c g)到 f 的部分,其实我们希望见到的结果是 a b f, 那么怎么把多余的d e去掉呢,其实很简单,在函数的最后一行加上个path.pop()就可以了,是不是很神奇。
完整代码如下:
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
ne = Node('e')
nf = Node('f')
ng = Node('g')
nd = Node('d'); nd.right = ne
nb = Node('b'); nb.left = nd; nb.right = nf
nc = Node('c'); nc.right = ng
root = Node('a'); root.left = nb; root.right = nc
def qianxu(root):
if not root: return
print(root.val, end=' ')
qianxu(root.left)
qianxu(root.right)
qianxu(root)
print()
def zhongxu(root):
if not root: return
zhongxu(root.left)
print(root.val, end=' ')
zhongxu(root.right)
zhongxu(root)
print()
def houxu(root):
if not root: return
houxu(root.left)
houxu(root.right)
print(root.val, end=' ')
houxu(root)
print()
path = []
def findPath(root, char):
if not root: return
path.append(root.val)
if root.val==char:
print(' '.join(path))
findPath(root.left, char)
findPath(root.right, char)
path.pop()
findPath(root, 'f')