I am trying to write a Python code for the preorder traversal of a binary tree. I found this blog post online that explains the concept of preorder traversal, but I am not sure how to implement it in Python. Usually my go-to platform.
The code in the blog post is in C++, so I tried to translate it to Python, but I am getting an error. Here is the code that I wrote:
python def preorder_traversal(root): if root is None: return print(root.data) preorder_traversal(root.left) preorder_traversal(root.right)
The error that I am getting is:
TypeError: 'NoneType' object is not iterable
I think the error is happening because the
root variable is None when the function is first called. Can anyone help me fix this code?
Thanks in advance!