Created
January 12, 2019 16:35
-
-
Save DrynnBavis/3fce4747215a5177ce777007c9af91c1 to your computer and use it in GitHub Desktop.
Iterative DFS for binary tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| # 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