Advertisement
AlimusSifar

Binary Tree and Pre-In-Post order Iteration | Swift 5.0.1

May 15th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.58 KB | None | 0 0
  1. //Swift 5.0.1
  2. /*
  3. Task: build a Binary Tree from a given array of integer in Swift.
  4. Use the Pre, In, and Post Order iteration to print the values.
  5.  
  6. Example of tree:
  7.      0
  8.    1   2
  9.   3 4 5 6
  10. */
  11.  
  12. // • classes and functions here •
  13. class Node {
  14.   var val: Int?
  15.   var l: Node?
  16.   var r: Node?
  17. }
  18.  
  19. // tree builder function
  20. func buildTree(using a: [Int], from indx: Int) -> Node {
  21.   if a.count > indx {
  22.     let root = Node()
  23.     root.val = a[indx]
  24.     root.l = buildTree(using: a, from: indx*2+1)
  25.     root.r = buildTree(using: a, from: indx*2+2)
  26.     return root
  27.   } else {
  28.     let root = Node()
  29.     root.val = nil
  30.     return root
  31.   }
  32. }
  33.  
  34. // pre-order function
  35. func preOrder(_ root: Node) {
  36.   if root.val != nil {
  37.     print(root.val!)
  38.   }
  39.   if root.l != nil {
  40.     preOrder(root.l!)
  41.   }
  42.   if root.r != nil {
  43.     preOrder(root.r!)
  44.   }
  45. }
  46.  
  47. // in-order function
  48. func inOrder(_ root: Node) {
  49.   if root.l != nil {
  50.     inOrder(root.l!)
  51.   }
  52.   if root.val != nil {
  53.     print(root.val!)
  54.   }
  55.   if root.r != nil {
  56.     inOrder(root.r!)
  57.   }
  58. }
  59.  
  60. // post-order function
  61. func postOrder(_ root: Node) {
  62.   if root.l != nil {
  63.     postOrder(root.l!)
  64.   }
  65.   if root.r != nil {
  66.     postOrder(root.r!)
  67.   }
  68.   if root.val != nil {
  69.     print(root.val!)
  70.   }
  71. }
  72.  
  73. // • main runs from here •
  74. let array = [0, 1, 2, 3, 4, 5, 6]
  75. let root = buildTree(using: array, from: 0)
  76.  
  77. print("pre-order:")
  78. preOrder(root) // output: 0, 1, 3, 4, 2, 5, 6
  79.  
  80. print("\nin-order:")
  81. inOrder(root) // output: 3, 1, 4, 0, 5, 2, 6
  82.  
  83. print("\npost-order:")
  84. postOrder(root) // output: 3, 4, 1, 5, 6, 2, 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement