My LeetCode grinding. Trying to do a problem a day.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

main.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Definition for a binary tree node.
  2. class TreeNode:
  3. def __init__(self, x):
  4. self.val = x
  5. self.left = None
  6. self.right = None
  7. class Solution:
  8. def mergeTrees(self, t1, t2):
  9. # One way to do this is construct an array representing each tree and then combine them one by one
  10. # index is established with: 2**level + position
  11. # so in tree:
  12. # 1
  13. # 2 3
  14. # 4 5 6 7
  15. # The numbers shown are the indexes
  16. # for construction is it important to note leftChild = 2 * current
  17. # and rightChild = 2 * current + 1
  18. # The tricky part will be ensuring the array is large enough, but we can pad with None's I suppose, probably not optimal
  19. # but it'll do, and I think be pretty error proof
  20. # Actually scratch all this, I think it shouldn't be too hard to build the tree as we traverse both simultaneously
  21. # might need to make a recursive function first though
  22. return self.mergeTreesRecursive(t1, t2)
  23. def mergeTreesRecursive(self, t1, t2):
  24. # base case is neither tree has a child to add
  25. if t1 is None and t2 is None:
  26. return None
  27. if t1 is None:
  28. newNode = TreeNode(t2.val)
  29. newNode.left = self.mergeTreesRecursive(t2.left, None)
  30. newNode.right = self.mergeTreesRecursive(t2.right, None)
  31. elif t2 is None:
  32. newNode = TreeNode(t1.val)
  33. newNode.left = self.mergeTreesRecursive(t1.left, None)
  34. newNode.right = self.mergeTreesRecursive(t1.right, None)
  35. else:
  36. newNode = TreeNode(t1.val + t2.val)
  37. newNode.left = self.mergeTreesRecursive(t1.left, t2.left)
  38. newNode.right = self.mergeTreesRecursive(t1.right, t2.right)
  39. return newNode
  40. s = Solution()
  41. print("Expected: Tree with root 3") # can't be bothered testing the whole tree
  42. t1 = TreeNode(1)
  43. t2 = TreeNode(2)
  44. print("Got: Tree with root", s.mergeTrees(t1, t2).val)