Python Forum
Python Code for Preorder Traversal of a Binary Tree
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Code for Preorder Traversal of a Binary Tree
#1
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!
Reply
#2
(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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UART write binary code trix 3 310 Apr-28-2024, 04:57 PM
Last Post: deanhystad
  How do I read and write a binary file in Python? blackears 6 7,107 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Binary tree AlexPython 3 1,022 Dec-07-2022, 06:41 AM
Last Post: ndc85430
  How to assigned value to each different binary in python... ZYSIA 2 2,081 Jul-12-2021, 11:01 AM
Last Post: Gribouillis
  Python3 binary tree not replacing parent nodes with child nodes Aspect11 0 1,801 Sep-23-2020, 02:22 PM
Last Post: Aspect11
  How to convert a python code to binary? rsurathu 0 1,830 Aug-02-2020, 08:09 AM
Last Post: rsurathu
  python read binary file Pyguys 4 3,960 Jul-13-2020, 02:34 AM
Last Post: Pyguys
  Is my Tree code too long? BladedSupernova 5 2,698 Feb-12-2020, 03:07 AM
Last Post: Larz60+
  Family Tree Project on Python? nuplix 1 7,024 Feb-11-2020, 02:54 AM
Last Post: Larz60+
  Simple text to binary python script gmills13 2 2,853 Feb-04-2020, 08:44 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020