12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- # Definition for a binary tree node.
- class TreeNode:
- def __init__(self, x):
- self.val = x
- self.left = None
- self.right = None
-
- class Solution:
- def mergeTrees(self, t1, t2):
- # One way to do this is construct an array representing each tree and then combine them one by one
- # index is established with: 2**level + position
- # so in tree:
- # 1
- # 2 3
- # 4 5 6 7
- # The numbers shown are the indexes
- # for construction is it important to note leftChild = 2 * current
- # and rightChild = 2 * current + 1
- # The tricky part will be ensuring the array is large enough, but we can pad with None's I suppose, probably not optimal
- # but it'll do, and I think be pretty error proof
-
- # Actually scratch all this, I think it shouldn't be too hard to build the tree as we traverse both simultaneously
- # might need to make a recursive function first though
-
- return self.mergeTreesRecursive(t1, t2)
-
- def mergeTreesRecursive(self, t1, t2):
-
- # base case is neither tree has a child to add
- if t1 is None and t2 is None:
- return None
-
- if t1 is None:
- newNode = TreeNode(t2.val)
- newNode.left = self.mergeTreesRecursive(t2.left, None)
- newNode.right = self.mergeTreesRecursive(t2.right, None)
- elif t2 is None:
- newNode = TreeNode(t1.val)
- newNode.left = self.mergeTreesRecursive(t1.left, None)
- newNode.right = self.mergeTreesRecursive(t1.right, None)
- else:
- newNode = TreeNode(t1.val + t2.val)
- newNode.left = self.mergeTreesRecursive(t1.left, t2.left)
- newNode.right = self.mergeTreesRecursive(t1.right, t2.right)
-
- return newNode
-
- s = Solution()
- print("Expected: Tree with root 3") # can't be bothered testing the whole tree
- t1 = TreeNode(1)
- t2 = TreeNode(2)
- print("Got: Tree with root", s.mergeTrees(t1, t2).val)
|