Python Forum

Full Version: Python Code for Preorder Traversal of a Binary Tree
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I'm currently working on implementing a preorder traversal, and I've been using the tutorial on preorder traversal for a binary tree in Python blog as a reference. However, I'm encountering some issues with my code, and I could use some guidance.

Here's the Python code I have so far:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def preorderTraversal(root):
    if root is None:
        return []
    
    result = []
    stack = [root]

    while stack:
        node = stack.pop()
        result.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    
    return result
I've followed the tutorial's steps closely, but I'm not getting the expected output. Could someone please review my code and point out any issues or suggest improvements? I'd greatly appreciate it!
(Sep-22-2023, 08:18 AM)Bolt Wrote: [ -> ]I've followed the tutorial's steps closely, but I'm not getting the expected output.
The code is incomplete: as it is it will produce no output. Can you post the complete code, the ouptut that you get and the output that you are expecting?