class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
if not root:
return None
stack.append(root)
res = []
while(stack):
node = stack[-1]
res.append(node.val)
stack.pop()
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
It is a best solution found that very popular and helpful:
https://www.youtube.com/watch?v=u2Py9rhxEuY&ab_channel=EricProgramming