分析: 1、初始化二叉树 2、如果t1不存在,返回t2;如果t1存在,t1的值=t1的值+t2的值;内部递归循环t1左子树和t1右子树,返回t1 3、赋值t1,t2,得出和 代码: #Definition for a binary tree node,初始化二叉树 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None #前序遍历(先遍历根节点,再遍历左子树,再遍历右子树) def preorder(root): if root: print(root.val) preorder(root.left) preorder(root.right) #中序遍历(先遍历左子树,再遍历根节点,再遍历右子树) def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) #后序遍历(先遍历左子树,再遍历右子树,再遍历根节点) def postorder(root): if root: postorder(root.left) postorder(root.right) print(root.val) class Solution(object): def mergeTrees(self, t1:TreeNode, t2:TreeNode): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1 and t2: return t2 elif t1 and t2: t1.val = t2.val+t1.val t1.left = self.mergeTrees(t1.left,t2.left) t1.right = self.mergeTrees(t1.right,t2.right) return t1 #赋值t1 Tree1 = TreeNode(1) Tree1.left = TreeNode(3) Tree1.right = TreeNode(2) Tree1.left.left = TreeNode(5) preorder(Tree1) #赋值t2 Tree2 = TreeNode(2) Tree2.left = TreeNode(1) Tree2.right = TreeNode(3) Tree2.left.right = TreeNode(4) Tree2.right.right=TreeNode(7) preorder(Tree2) 实例运行 s = Solution() res = s.mergeTrees(Tree1,Tree2) print(res) preorder(res) 运行结果:
1 3 5 2 2 1 4 3 7 <__main__.TreeNode object at 0x000001745567C128> 3 4 5 4 5 7 Process finished with exit code 0
题目要求 ''' 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。 示例 1: 输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7 注意: 合并必须从两个树的根节点开始。 '''
python mergeTrees合并二叉树
最新推荐文章于 2022-11-26 00:18:17 发布