-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.py
More file actions
38 lines (29 loc) · 1.06 KB
/
BinaryTreeInorderTraversal.py
File metadata and controls
38 lines (29 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import Optional, List
"""
pseudoCode
start at the root of a binary tree
traverse the left subtree
empty? backtrack to the root and add its value to the stack []
we will run the same steps recursively
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = [] # this is where we store the node values and has nothing to do with the actual stack of the DFS Algorithm
# the stack is actually
# managed by Python's call stack during recursion
# this is the recursive approach
def inorder(root):
if not root:
return
# if there is a root, traverse the tree
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root) # start the traversal from the root
return res