class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class ForestNode:
def __init__(self, val):
self.val = val
self.children = []
def forest_to_binary_tree(forest):
if not forest:
return None
def convert(root):
if not root:
return None
node = TreeNode(root.val)
if root.children:
node.left = convert(root.children[0])
current = node.left
for child in root.children[1:]:
current.right = convert(child)
current = current.right
return node
dummy = TreeNode(None)
current = dummy
for tree in forest:
current.right = convert(tree)
current = current.right
return dummy.right
def binary_tree_to_forest(root):
if not root:
return []
def convert(node):
if not node:
return None
forest_node = ForestNode(node.val)
if node.left:
forest_node.children.append(convert(node.left))
current = node.left
while current and current.right:
forest_node.children.append(convert(current.right))
current = current.right
return forest_node
forest = []
current = root
while current:
forest.append(convert(current))
current = current.right
return forest