Created
May 24, 2023 12:41
-
-
Save harryscholes/75d1ff6ea664fff8d511df2ea30ad39c to your computer and use it in GitHub Desktop.
Right view of a binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, value=None, left=None, right=None): | |
self.value = value | |
self.left = left | |
self.right = right | |
def __repr__(self): | |
return str(self.value) | |
def right_view(tree): | |
viewing_depth = 0 | |
ans = [] | |
queue = [(tree, 0)] | |
while len(queue) > 0: | |
node, depth = queue.pop(0) | |
if node is not None: | |
if depth == viewing_depth: | |
ans.append(node.value) | |
viewing_depth += 1 | |
queue.append((node.right, depth + 1)) | |
queue.append((node.left, depth + 1)) | |
return ans | |
def right_view(tree): | |
ans = [] | |
width = 1 | |
queue = [tree] | |
while len(queue) > 0: | |
level, queue = queue[:width], queue[width:] | |
width = 0 | |
seen = False | |
for node in level: | |
if node is not None: | |
queue.append(node.right) | |
queue.append(node.left) | |
width += 2 | |
if not seen: | |
ans.append(node.value) | |
seen = True | |
return ans | |
t1 = None | |
t2 = Node( | |
1, | |
left=Node( | |
2, | |
right=Node( | |
5, | |
left=Node(4), | |
), | |
), | |
right=Node( | |
3, | |
left=Node(6), | |
), | |
) | |
t3 = Node( | |
1, | |
left=Node( | |
2, | |
left=Node(4), | |
), | |
right=Node( | |
3, | |
left=Node(5), | |
right=Node( | |
6, | |
left=Node(7) | |
), | |
), | |
) | |
assert right_view(t1) == [] | |
assert right_view(t2) == [1, 3, 6, 4] | |
assert right_view(t3) == [1, 3, 6, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment