Skip to content

Commit d4f2873

Browse files
add reverse_inorder traversal to binary_tree_traversals.py (TheAlgorithms#8726)
* add reverse_inorder traversal to binary_tree_traversals.py * Apply suggestions from code review Co-authored-by: Tianyi Zheng <[email protected]> --------- Co-authored-by: Tianyi Zheng <[email protected]>
1 parent 8b831cb commit d4f2873

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

data_structures/binary_tree/binary_tree_traversals.py

+16-6
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,19 @@ def inorder(root: Node | None) -> list[int]:
5858
return [*inorder(root.left), root.data, *inorder(root.right)] if root else []
5959

6060

61+
def reverse_inorder(root: Node | None) -> list[int]:
62+
"""
63+
Reverse in-order traversal visits right subtree, root node, left subtree.
64+
>>> reverse_inorder(make_tree())
65+
[3, 1, 5, 2, 4]
66+
"""
67+
return (
68+
[*reverse_inorder(root.right), root.data, *reverse_inorder(root.left)]
69+
if root
70+
else []
71+
)
72+
73+
6174
def height(root: Node | None) -> int:
6275
"""
6376
Recursive function for calculating the height of the binary tree.
@@ -161,15 +174,12 @@ def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]:
161174

162175

163176
def main() -> None: # Main function for testing.
164-
"""
165-
Create binary tree.
166-
"""
177+
# Create binary tree.
167178
root = make_tree()
168-
"""
169-
All Traversals of the binary are as follows:
170-
"""
171179

180+
# All Traversals of the binary are as follows:
172181
print(f"In-order Traversal: {inorder(root)}")
182+
print(f"Reverse In-order Traversal: {reverse_inorder(root)}")
173183
print(f"Pre-order Traversal: {preorder(root)}")
174184
print(f"Post-order Traversal: {postorder(root)}", "\n")
175185

0 commit comments

Comments
 (0)