将二叉树追加到另一个二叉树可以通过以下步骤完成:
以下是一个示例代码,演示如何将一个二叉树追加到另一个二叉树:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def append_tree(target_tree, append_tree):
if target_tree is None:
return append_tree
if append_tree is None:
return target_tree
target_tree.left = append_tree(target_tree.left, append_tree.left)
target_tree.right = append_tree(target_tree.right, append_tree.right)
return target_tree
# 创建两个二叉树
tree1 = TreeNode(1)
tree1.left = TreeNode(2)
tree1.right = TreeNode(3)
tree2 = TreeNode(4)
tree2.left = TreeNode(5)
tree2.right = TreeNode(6)
# 将tree2追加到tree1
append_tree(tree1, tree2)
这段代码将tree2追加到tree1的左子树上,最终tree1的结构如下:
1
/ \
4 3
/ \
5 6
这是一个简单的示例,实际应用中可能需要根据具体情况进行调整。
领取专属 10元无门槛券
手把手带您无忧上云