mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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:
parent
8b831cb600
commit
d4f2873e39
|
@ -58,6 +58,19 @@ def inorder(root: Node | None) -> list[int]:
|
||||||
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 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:
|
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.
|
||||||
|
@ -161,15 +174,12 @@ def zigzag(root: Node | None) -> Sequence[Node | None] | list[Any]:
|
||||||
|
|
||||||
|
|
||||||
def main() -> None: # Main function for testing.
|
def main() -> None: # Main function for testing.
|
||||||
"""
|
# Create binary tree.
|
||||||
Create binary tree.
|
|
||||||
"""
|
|
||||||
root = make_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"In-order Traversal: {inorder(root)}")
|
||||||
|
print(f"Reverse In-order Traversal: {reverse_inorder(root)}")
|
||||||
print(f"Pre-order Traversal: {preorder(root)}")
|
print(f"Pre-order Traversal: {preorder(root)}")
|
||||||
print(f"Post-order Traversal: {postorder(root)}", "\n")
|
print(f"Post-order Traversal: {postorder(root)}", "\n")
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user