目录
多叉树转换为二叉树
二叉树结点采用孩子兄弟链结构存储,把多叉树的第一棵子树转换的二叉树作为二叉树根的第一个孩子,把多叉树的第二棵子树转换的二叉树作为二叉树的第一个孩子的兄弟,把多叉树的第三棵子树转换的二叉树作为其第二棵子树转换的二叉树的兄弟,以此类推
class Node:
def __init__(self, val = 'null'):
self.val = val
self.children = []
def __str__(self):
return self.val
class BinNode:
firstchild = None
nextsibling = None
def __init__(self, val = 'null'):
self.val = val
def __str__(self):
return self.val
def multi2bintree(root):
broot = BinNode(root.val)
if not root.children:
return broot
firstchild = root.children[0]
broot.firstchild = multi2bintree(firstchild)
prev = broot.firstchild
for i in range(1, len(root.children)):
prev.nextsibling = multi2bintree(root.children[i])
prev = prev.nextsibling
return broot
二叉树转换为多叉树
把二叉树的第一棵子树转换成的多叉树作为多叉树的第一棵子树,把二叉树第一棵子树的兄弟树转换成的多叉树作为多叉树的第二棵子树,把二叉树的第一棵子树的兄弟树的兄弟树转换成的多叉树作为多叉树的第三棵子树,依次类推
def bin2multitree(root):
if not root:
return None
mroot = Node(root.val)
if not root.firstchild:
return mroot
child = bin2multitree(root.firstchild)
mroot.children.append(child)
nextsibling = root.firstchild.nextsibling
while nextsibling:
child = bin2multitree(nextsibling)
mroot.children.append(child)
nextsibling = nextsibling.nextsibling
return mroot
森林转化为二叉树
把森林中的每一棵多叉树转换为一棵二叉树,然后把这些二叉树以兄弟链的形式结合在一起即得
def forest2bintree(forest):
if not forest:
return None
bintrees = []
for tree in forest:
bintrees.append(multi2bintree(tree))
prev = root = bintrees[0]
for i in range(1, len(bintrees)):
curr = bintrees[i]
prev.nextsibling = curr
prev = curr
return root
二叉树转换为森林
把二叉树沿着兄弟链拆成一个右子树为空的二叉树集合,把每一个二叉树转换成多叉树即得。
def bintree2forest(root):
forest = []
while root:
nextsibling = root.nextsibling
root.nextsibling = None
forest.append(bin2multitree(root))
root = nextsibling
return forest