From af1180e6c407f84fac00f2b5f202d486d09b7239 Mon Sep 17 00:00:00 2001 From: Amirsoroush Date: Fri, 12 May 2023 23:56:50 +0300 Subject: [PATCH 1/2] add reverse_inorder traversal to binary_tree_traversals.py --- .../binary_tree/binary_tree_traversals.py | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/data_structures/binary_tree/binary_tree_traversals.py b/data_structures/binary_tree/binary_tree_traversals.py index 71a895e76ce4..d5db0a3edff3 100644 --- a/data_structures/binary_tree/binary_tree_traversals.py +++ b/data_structures/binary_tree/binary_tree_traversals.py @@ -58,6 +58,19 @@ def inorder(root: Node | None) -> list[int]: return [*inorder(root.left), root.data, *inorder(root.right)] if root else [] +def reverse_inorder(root: Node | None) -> list[int]: + """ + Reverse in-order traversal visits right subtree, root node, left subtree. + >>> reverse_inorder(make_tree()) + [3, 1, 5, 2, 4] + """ + return ( + [*reverse_inorder(root.right), root.data, *reverse_inorder(root.left)] + if root + else [] + ) + + def height(root: Node | None) -> int: """ Recursive function for calculating the height of the binary tree. @@ -161,14 +174,10 @@ def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]: def main() -> None: # Main function for testing. - """ - Create binary tree. - """ + # Create binary tree. root = make_tree() - """ - All Traversals of the binary are as follows: - """ + # All Traversals of the binary are as follows: print(f"In-order Traversal: {inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n") From dfcc27b41c8eb9c79e41a90b0f777dddaf4c2a45 Mon Sep 17 00:00:00 2001 From: AmirSoroush <114881632+amirsoroush@users.noreply.github.com> Date: Tue, 16 May 2023 11:05:39 +0300 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: Tianyi Zheng --- data_structures/binary_tree/binary_tree_traversals.py | 1 + 1 file changed, 1 insertion(+) diff --git a/data_structures/binary_tree/binary_tree_traversals.py b/data_structures/binary_tree/binary_tree_traversals.py index d5db0a3edff3..2afb7604f9c6 100644 --- a/data_structures/binary_tree/binary_tree_traversals.py +++ b/data_structures/binary_tree/binary_tree_traversals.py @@ -179,6 +179,7 @@ def main() -> None: # Main function for testing. # All Traversals of the binary are as follows: print(f"In-order Traversal: {inorder(root)}") + print(f"Reverse In-order Traversal: {reverse_inorder(root)}") print(f"Pre-order Traversal: {preorder(root)}") print(f"Post-order Traversal: {postorder(root)}", "\n")