add reverse_inorder traversal to binary_tree_traversals.py (#8726)

* add reverse_inorder traversal to binary_tree_traversals.py

* Apply suggestions from code review

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>

---------

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
This commit is contained in:
AmirSoroush 2023-07-31 03:54:15 +03:00 committed by GitHub
parent 8b831cb600
commit d4f2873e39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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,15 +174,12 @@ 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"Reverse In-order Traversal: {reverse_inorder(root)}")
print(f"Pre-order Traversal: {preorder(root)}")
print(f"Post-order Traversal: {postorder(root)}", "\n")