fork download
  1. class TreeNode:
  2. def __init__(self, value):
  3. self.value = value
  4. self.children = [] # List of child nodes
  5.  
  6. # Recursive DFS Function
  7. def dfs_recursive(node):
  8. if node is None:
  9. return
  10. print(node.value, end=" ") # Process the current node
  11. for child in node.children:
  12. dfs_recursive(child)
  13.  
  14. # Iterative DFS Function
  15. def dfs_iterative(node):
  16. if node is None:
  17. return
  18. stack = [node] # Initialize stack with the root node
  19. while stack:
  20. current = stack.pop()
  21. print(current.value, end=" ") # Process the current node
  22. # Add children to the stack in reverse order (rightmost child first)
  23. stack.extend(reversed(current.children))
  24.  
  25. # Build the tree as per the image
  26. root = TreeNode(1)
  27. child2 = TreeNode(2)
  28. child7 = TreeNode(7)
  29. child8 = TreeNode(8)
  30.  
  31. child2.children = [TreeNode(3), TreeNode(6)]
  32. child2.children[0].children = [TreeNode(4), TreeNode(5)]
  33.  
  34. child7.children = [TreeNode(9)]
  35. child7.children[0].children = [TreeNode(10)]
  36.  
  37. child8.children = [TreeNode(12), TreeNode(11)]
  38.  
  39. root.children = [child2, child7, child8]
  40.  
  41. # Run DFS
  42. print("Recursive DFS Traversal:")
  43. dfs_recursive(root)
  44.  
  45. print("\nIterative DFS Traversal:")
  46. dfs_iterative(root)
  47.  
Success #stdin #stdout #stderr 0.24s 40864KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "class TreeNode"
Execution halted