Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Swift 5.0.1
- /*
- Task: build a Binary Tree from a given array of integer in Swift.
- Use the Pre, In, and Post Order iteration to print the values.
- Example of tree:
- 0
- 1 2
- 3 4 5 6
- */
- // • classes and functions here •
- class Node {
- var val: Int?
- var l: Node?
- var r: Node?
- }
- // tree builder function
- func buildTree(using a: [Int], from indx: Int) -> Node {
- if a.count > indx {
- let root = Node()
- root.val = a[indx]
- root.l = buildTree(using: a, from: indx*2+1)
- root.r = buildTree(using: a, from: indx*2+2)
- return root
- } else {
- let root = Node()
- root.val = nil
- return root
- }
- }
- // pre-order function
- func preOrder(_ root: Node) {
- if root.val != nil {
- print(root.val!)
- }
- if root.l != nil {
- preOrder(root.l!)
- }
- if root.r != nil {
- preOrder(root.r!)
- }
- }
- // in-order function
- func inOrder(_ root: Node) {
- if root.l != nil {
- inOrder(root.l!)
- }
- if root.val != nil {
- print(root.val!)
- }
- if root.r != nil {
- inOrder(root.r!)
- }
- }
- // post-order function
- func postOrder(_ root: Node) {
- if root.l != nil {
- postOrder(root.l!)
- }
- if root.r != nil {
- postOrder(root.r!)
- }
- if root.val != nil {
- print(root.val!)
- }
- }
- // • main runs from here •
- let array = [0, 1, 2, 3, 4, 5, 6]
- let root = buildTree(using: array, from: 0)
- print("pre-order:")
- preOrder(root) // output: 0, 1, 3, 4, 2, 5, 6
- print("\nin-order:")
- inOrder(root) // output: 3, 1, 4, 0, 5, 2, 6
- print("\npost-order:")
- postOrder(root) // output: 3, 4, 1, 5, 6, 2, 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement