[mypy] Fix type annotations for binary tree traversals in data structures (#5556)

* [mypy] Fix type annotations for binary tree traversals in data structures

* Change variable name and update level_order_1 to use a deque

Using a deque instead of a list here, because since we are removing from the beginning of the list, the deque will be more efficient.

* remove duplicate function

* Update data_structures/binary_tree/binary_tree_traversals.py

Co-authored-by: John Law <johnlaw.po@gmail.com>

* fix function name at line 137

* Update data_structures/binary_tree/binary_tree_traversals.py

Co-authored-by: John Law <johnlaw.po@gmail.com>

* Update data_structures/binary_tree/binary_tree_traversals.py

Co-authored-by: John Law <johnlaw.po@gmail.com>

* Remove type alias and use the new syntax

* Update data_structures/binary_tree/binary_tree_traversals.py

Co-authored-by: John Law <johnlaw.po@gmail.com>

* Remove prints inside functions and return lists

Co-authored-by: John Law <johnlaw.po@gmail.com>
This commit is contained in:
Dylan Buchi 2021-10-28 11:05:31 -03:00 committed by GitHub
parent 6b6762bde9
commit bf6db32ec2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,7 +1,9 @@
# https://en.wikipedia.org/wiki/Tree_traversal # https://en.wikipedia.org/wiki/Tree_traversal
from __future__ import annotations from __future__ import annotations
from collections import deque
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Sequence
@dataclass @dataclass
@ -11,11 +13,11 @@ class Node:
right: Node | None = None right: Node | None = None
def make_tree() -> Node: def make_tree() -> Node | None:
return Node(1, Node(2, Node(4), Node(5)), Node(3)) return Node(1, Node(2, Node(4), Node(5)), Node(3))
def preorder(root: Node): def preorder(root: Node | None) -> list[int]:
""" """
Pre-order traversal visits root node, left subtree, right subtree. Pre-order traversal visits root node, left subtree, right subtree.
>>> preorder(make_tree()) >>> preorder(make_tree())
@ -24,7 +26,7 @@ def preorder(root: Node):
return [root.data] + preorder(root.left) + preorder(root.right) if root else [] return [root.data] + preorder(root.left) + preorder(root.right) if root else []
def postorder(root: Node): def postorder(root: Node | None) -> list[int]:
""" """
Post-order traversal visits left subtree, right subtree, root node. Post-order traversal visits left subtree, right subtree, root node.
>>> postorder(make_tree()) >>> postorder(make_tree())
@ -33,7 +35,7 @@ def postorder(root: Node):
return postorder(root.left) + postorder(root.right) + [root.data] if root else [] return postorder(root.left) + postorder(root.right) + [root.data] if root else []
def inorder(root: Node): def inorder(root: Node | None) -> list[int]:
""" """
In-order traversal visits left subtree, root node, right subtree. In-order traversal visits left subtree, root node, right subtree.
>>> inorder(make_tree()) >>> inorder(make_tree())
@ -42,7 +44,7 @@ def inorder(root: Node):
return inorder(root.left) + [root.data] + inorder(root.right) if root else [] return inorder(root.left) + [root.data] + inorder(root.right) if root else []
def height(root: Node): def height(root: Node | None) -> int:
""" """
Recursive function for calculating the height of the binary tree. Recursive function for calculating the height of the binary tree.
>>> height(None) >>> height(None)
@ -53,80 +55,99 @@ def height(root: Node):
return (max(height(root.left), height(root.right)) + 1) if root else 0 return (max(height(root.left), height(root.right)) + 1) if root else 0
def level_order_1(root: Node): def level_order(root: Node | None) -> Sequence[Node | None]:
""" """
Print whole binary tree in Level Order Traverse. Returns a list of nodes value from a whole binary tree in Level Order Traverse.
Level Order traverse: Visit nodes of the tree level-by-level. Level Order traverse: Visit nodes of the tree level-by-level.
""" """
if not root: output: list[Any] = []
return
temp = root if root is None:
que = [temp] return output
while len(que) > 0:
print(que[0].data, end=" ") process_queue = deque([root])
temp = que.pop(0)
if temp.left: while process_queue:
que.append(temp.left) node = process_queue.popleft()
if temp.right: output.append(node.data)
que.append(temp.right)
return que if node.left:
process_queue.append(node.left)
if node.right:
process_queue.append(node.right)
return output
def level_order_2(root: Node, level: int): def get_nodes_from_left_to_right(
root: Node | None, level: int
) -> Sequence[Node | None]:
""" """
Level-wise traversal: Print all nodes present at the given level of the binary tree Returns a list of nodes value from a particular level:
Left to right direction of the binary tree.
""" """
if not root: output: list[Any] = []
return root
if level == 1:
print(root.data, end=" ")
elif level > 1:
level_order_2(root.left, level - 1)
level_order_2(root.right, level - 1)
def populate_output(root: Node | None, level: int) -> None:
def print_left_to_right(root: Node, level: int):
"""
Print elements on particular level from left to right direction of the binary tree.
"""
if not root: if not root:
return return
if level == 1: if level == 1:
print(root.data, end=" ")
output.append(root.data)
elif level > 1: elif level > 1:
print_left_to_right(root.left, level - 1) populate_output(root.left, level - 1)
print_left_to_right(root.right, level - 1) populate_output(root.right, level - 1)
populate_output(root, level)
return output
def print_right_to_left(root: Node, level: int): def get_nodes_from_right_to_left(
root: Node | None, level: int
) -> Sequence[Node | None]:
""" """
Print elements on particular level from right to left direction of the binary tree. Returns a list of nodes value from a particular level:
Right to left direction of the binary tree.
""" """
if not root: output: list[Any] = []
def populate_output(root: Node | None, level: int) -> None:
if root is None:
return return
if level == 1: if level == 1:
print(root.data, end=" ") output.append(root.data)
elif level > 1: elif level > 1:
print_right_to_left(root.right, level - 1) populate_output(root.right, level - 1)
print_right_to_left(root.left, level - 1) populate_output(root.left, level - 1)
populate_output(root, level)
return output
def zigzag(root: Node): def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]:
""" """
ZigZag traverse: Print node left to right and right to left, alternatively. ZigZag traverse:
Returns a list of nodes value from left to right and right to left, alternatively.
""" """
if root is None:
return []
output: list[Sequence[Node | None]] = []
flag = 0 flag = 0
height_tree = height(root) height_tree = height(root)
for h in range(1, height_tree + 1): for h in range(1, height_tree + 1):
if flag == 0: if not flag:
print_left_to_right(root, h) output.append(get_nodes_from_left_to_right(root, h))
flag = 1 flag = 1
else: else:
print_right_to_left(root, h) output.append(get_nodes_from_right_to_left(root, h))
flag = 0 flag = 0
return output
def main(): # Main function for testing.
def main() -> None: # Main function for testing.
""" """
Create binary tree. Create binary tree.
""" """
@ -134,18 +155,23 @@ def main(): # Main function for testing.
""" """
All Traversals of the binary are as follows: All Traversals of the binary are as follows:
""" """
print(f" In-order Traversal is {inorder(root)}")
print(f" Pre-order Traversal is {preorder(root)}") print(f"In-order Traversal: {inorder(root)}")
print(f"Post-order Traversal is {postorder(root)}") print(f"Pre-order Traversal: {preorder(root)}")
print(f"Height of Tree is {height(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n")
print("Complete Level Order Traversal is : ")
level_order_1(root) print(f"Height of Tree: {height(root)}", "\n")
print("\nLevel-wise order Traversal is : ")
for h in range(1, height(root) + 1): print("Complete Level Order Traversal: ")
level_order_2(root, h) print(level_order(root), "\n")
print("\nZigZag order Traversal is : ")
zigzag(root) print("Level-wise order Traversal: ")
print()
for level in range(1, height(root) + 1):
print(f"Level {level}:", get_nodes_from_left_to_right(root, level=level))
print("\nZigZag order Traversal: ")
print(zigzag(root))
if __name__ == "__main__": if __name__ == "__main__":