Python code for preorder traversal of a binary tree

Hi everyone,

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!

Is there more code? How are you calling the function and what data are you giving it?

This looks pretty good, but it’s just an implementation of the algorithm. What does the first line do?

python

Also, you could add print(root) before your IF statement for debugging.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.