Skip to content

Instantly share code, notes, and snippets.

@DrynnBavis
Created January 12, 2019 16:35
Show Gist options
  • Select an option

  • Save DrynnBavis/3fce4747215a5177ce777007c9af91c1 to your computer and use it in GitHub Desktop.

Select an option

Save DrynnBavis/3fce4747215a5177ce777007c9af91c1 to your computer and use it in GitHub Desktop.
Iterative DFS for binary tree
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
stack = []
result = []
if root is not None:
stack.append(root)
while len(stack) != 0:
node = stack.pop()
result.append(node.val)
if len(node.children) != 0:
for x in node.children[::-1]:
stack.append(x)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment