【leetcode】617. Merge Two Binary Trees
题目如下:
解题思路:非常简单的一个题目,创建新的树根节点newNode,然后先遍历t1,把t1复制一遍给newNode;接下来遍历t2,如果t2和newNode两者对应的相同位置的节点都存在,那么newNode对应位置的节点的值加上t2对应的值;如果newNode不存在,则创建一个和t2对应位置的节点值一样的新节点。
代码如下:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def traverse(self,newNode,node): if node.left != None: if newNode.left == None: newNode.left = TreeNode(node.left.val) else: newNode.left.val += node.left.val self.traverse(newNode.left,node.left) if node.right != None: if newNode.right == None: newNode.right = TreeNode(node.right.val) else: newNode.right.val += node.right.val self.traverse(newNode.right, node.right) def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ root = None if t1 == t2 == None: return None if t1 != None: root = TreeNode(t1.val) self.traverse(root,t1) if t2 != None: if root == None: root = TreeNode(t2.val) else: root.val += t2.val self.traverse(root, t2) return root