Skip to content

Commit 04b6d55

Browse files
committed
Added a python file to Implement Preorder, Inorder, and Postorder traversals in one traversal.
1 parent 4baa72b commit 04b6d55

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

data_structures/binary_tree/all_traversals_one_pass.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
of a binary tree in a single traversal using an iterative approach with a stack.
66
"""
77

8-
from typing import Optional, List, Tuple
8+
from __future__ import annotations
99

1010

1111
class Node:
@@ -20,17 +20,16 @@ class Node:
2020
The left child of the node.
2121
right : Node, optional
2222
The right child of the node.
23-
2423
Reference: https://en.wikipedia.org/wiki/Binary_tree
2524
"""
2625

2726
def __init__(self, data: int):
2827
self.data = data
29-
self.left: Optional[Node] = None
30-
self.right: Optional[Node] = None
28+
self.left: Node | None = None
29+
self.right: Node | None = None
3130

3231

33-
def all_traversals(root: Optional[Node]) -> Tuple[List[int], List[int], List[int]]:
32+
def all_traversals(root: Node | None) -> tuple[list[int], list[int], list[int]]:
3433
"""
3534
Perform Preorder, Inorder, and Postorder traversals in a single pass.
3635
@@ -78,8 +77,10 @@ def all_traversals(root: Optional[Node]) -> Tuple[List[int], List[int], List[int
7877
if root is None:
7978
return [], [], []
8079

81-
stack: List[Tuple[Node, int]] = [(root, 1)] # (node, state)
82-
preorder, inorder, postorder = [], [], []
80+
stack: list[tuple[Node, int]] = [(root, 1)] # (node, state)
81+
preorder: list[int] = []
82+
inorder: list[int] = []
83+
postorder: list[int] = []
8384

8485
while stack:
8586
node, state = stack.pop()

0 commit comments

Comments
 (0)