Skip to content

add reverse_inorder traversal to binary_tree_traversals.py #8726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 31, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions data_structures/binary_tree/binary_tree_traversals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand Down