Sep-22-2023, 08:18 AM
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:
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 resultI'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!