Selaa lähdekoodia

New problem done

master
Lachlan Jacob 5 vuotta sitten
vanhempi
commit
e3ee09e84c
3 muutettua tiedostoa jossa 79 lisäystä ja 0 poistoa
  1. 52
    0
      problems/617/main.py
  2. 24
    0
      problems/617/problem.txt
  3. 3
    0
      problems/617/run.sh

+ 52
- 0
problems/617/main.py Näytä tiedosto

@@ -0,0 +1,52 @@
# 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)

+ 24
- 0
problems/617/problem.txt Näytä tiedosto

@@ -0,0 +1,24 @@
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7


Note: The merging process must start from the root nodes of both trees.

+ 3
- 0
problems/617/run.sh Näytä tiedosto

@@ -0,0 +1,3 @@
#!/bin/bash

python3 main.py

Loading…
Peruuta
Tallenna