Part B References

LeetCode for Part B

In general: (sort by easy difficulty)

LeetCode Queues

LeetCode Trees

NOTE 1: on LeetCode root usually can also be None

NOTE 2: on LeetCode self is reserved for the test runner, ignore it

NOTE 3: if you try the algorithms on your computer, you will want to add these __str__ and __repr__ methods to TreeNode:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __str__(self):

        """ Returns a pretty string of the tree """
        def str_branches(node, branches):
            """ Returns a string with the tree pretty printed.

                branches: a list of characters representing the parent branches. Characters can be either ` ` or '│'
            strings = [str(node.val)]

            i = 0
            if node.left != None or node.right != None:
                for current in [node.left, node.right]:
                    if i == 0:
                        joint = '├'
                        joint = '└'

                    for b in branches:
                    if i == 0:
                        branches.append(' ')

                    if current != None:
                        strings.append(str_branches(current, branches))
                    i += 1
            return "".join(strings)

        return str_branches(self, [])

    def __repr__(self):
        return self.__str__()

NOTE 4: testcases are expressed as a list, which doesn’t tell much how the tree is structured. To see a visualization of the tree, when you get an error you can copy paste the ‘Input’ testcase into this tab and turn on the Tree Visualizer selector:


Trees exercises on LeetCode (sort by easy difficulty), for example:

LeetCode Graphs

Geeks for geeks

NOTE: required outputs are a bit strange, often times they ask you to print stuff while in fact you just need to return some data.

Geeks for geeks Queues

Geeks for geeks Graphs

NOTE: if they require you to produce stuff like matrices they are shown as a line of numbers but you have to return the actual Python matrix

DO NOT print anything

[ ]: