SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Data Structures In Scala


           Meetu Maltiar
        Principal Consultant
              Knoldus
Agenda


Queue
Binary Tree
Binary Tree Traversals
Functional Queue

Functional Queue is a data structure that has three
operations:
 head: returns first element of the Queue
 tail: returns a Queue without its Head
 enqueue: returns a new Queue with given element at Head
 Has therefore First In First Out (FIFO) property
Functional Queue Continued
scala> val q = scala.collection.immutable.Queue(1, 2, 3)
q: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)


scala> val q1 = q enqueue 4
q1: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)


scala> q
res3: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)


scala> q1
res4: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)
Simple Queue Implementation
class SlowAppendQueue[T](elems: List[T]) {

    def head = elems.head

    def tail = new SlowAppendQueue(elems.tail)

    def enqueue(x: T) = new SlowAppendQueue(elems ::: List(x))

}




Head and tail operations are fast. Enqueue operation is slow as its performance is
directly proportional to number of elements.
Queue Optimizing Enqueue
class SlowHeadQueue[T](smele: List[T]) {
  // smele is elems reversed

    def head = smele.last // Not efficient

    def tail = new SlowHeadQueue(smele.init) // Not efficient

    def enqueue(x: T) = new SlowHeadQueue(x :: smele)
}



smele is elems reversed. Head operation is not efficient. Neither is tail operation. As both
last and init performance is directly proportional to number of elements in Queue
Functional Queue
class Queue[T](private val leading: List[T], private val trailing:
List[T]) {

    private def mirror =
      if (leading.isEmpty) new Queue(trailing.reverse, Nil)
      else this

    def head = mirror.leading.head

    def tail = {
      val q = mirror
      new Queue(q.leading.tail, q.trailing)
    }

    def enqueue(x: T) = new Queue(leading, x :: trailing)
}
Binary Search Tree

BST is organized tree.

BST has nodes one of them is specified as Root node.

Each node in BST has not more than two Children.

Each Child is also a Sub-BST.

Child is a leaf if it just has a root.
Binary Search Property

The keys in Binary Search Tree is stored to satisfy
following property:

Let x be a node in BST.
If y is a node in left subtree of x
Then Key[y] less than equal key[x]

If y is a node in right subtree of x
Then key[x] less than equal key[y]
Binary Search Property

        The Key of the root is 6

        The keys 2, 5 and 5 in left subtree is no
        larger than 6.

        The key 5 in root left child is no smaller
        than the key 2 in that node's left
        subtree and no larger than key 5 in the
        right sub tree
Tree Scala Representation
case class Tree[+T](value: T, left:
Option[Tree[T]], right: Option[Tree[T]])

This Tree representation is a recursive definition and has type
parameterization and is covariant due to is [+T] signature

This Tree class definition has following properties:
1. Tree has value of the given node
2. Tree has left sub-tree and it may have or do not contain value
3. Tree has right sub-tree and it may have or do not contain value

It is covariant to allow subtypes to be contained in the Tree
Tree In-order Traversal
BST property enables us to print out all
the Keys in a sorted order using simple
recursive In-order traversal.

It is called In-Order because it prints
key of the root of a sub-tree between
printing of the values in its left sub-
tree and printing those in its right sub-
tree
Tree In-order Algorithm
INORDER-TREE-WALK(x)
1. if x != Nil
2.   INORDER-TREE-WALK(x.left)
3.   println x.key
4.   INORDER-TREE-WALK(x.right)


For our BST in example before the output expected will be:
255678
Tree In-order Scala
  def inOrder[A](t: Option[Tree[A]], f: Tree[A] =>
Unit): Unit = t match {
    case None =>
    case Some(x) =>
      if (x.left != None) inOrder(x.left, f)
      f(x)
      if (x.right != None) inOrder(x.right, f)
  }
Tree Pre-order Algorithm
PREORDER-TREE-WALK(x)
1. if x != Nil
2.   println x.key
3.   PREORDER-TREE-WALK(x.left)
4.   PREORDER-TREE-WALK(x.right)


For our BST in example before the output expected will be:
652578
Tree Pre-order Scala
def preOrder[A](t: Option[Tree[A]], f: Tree[A]
=> Unit): Unit = t match {
    case None =>
    case Some(x) =>
      f(x)
      if (x.left != None) inOrder(x.left, f)
      if (x.right != None) inOrder(x.right, f)
  }



Pre-Order traversal is good for creating a copy of the Tree
Tree Post-Order Algorithm
POSTORDER-TREE-WALK(x)
1. if x != Nil
2.   POSTORDER-TREE-WALK(x.left)
3.   POSTORDER-TREE-WALK(x.right)
4.   println x.key

For our BST in example before the output expected will be:
255876

Useful in deleting a tree. In order to free up resources a
node in the tree can only be deleted if all the children (left
and right) are also deleted

Post-Order does exactly that. It processes left and right
sub-trees before processing current node
Tree Post-order Scala
def postOrder[A](t: Option[Tree[A]], f: Tree[A]
=> Unit): Unit = t match {
    case None =>
    case Some(x) =>
      if (x.left != None) postOrder(x.left, f)
      if (x.right != None) postOrder(x.right, f)
      f(x)
  }
References
1. Cormen Introduction to Algorithms

2. Binary Search Trees Wikipedia

3. Martin Odersky “Programming In Scala”

4. Daniel spiewak talk “Extreme Cleverness:
Functional Data Structures In Scala”
Thank You!!

Weitere ähnliche Inhalte

Was ist angesagt?

Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
Sajid Marwat
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
MongoDB
 

Was ist angesagt? (20)

Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
 
Spark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark MeetupSpark SQL Deep Dive @ Melbourne Spark Meetup
Spark SQL Deep Dive @ Melbourne Spark Meetup
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
Understanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache CassandraUnderstanding Data Partitioning and Replication in Apache Cassandra
Understanding Data Partitioning and Replication in Apache Cassandra
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Heap sort
Heap sortHeap sort
Heap sort
 
Lecture 5 sorting and searching
Lecture 5   sorting and searchingLecture 5   sorting and searching
Lecture 5 sorting and searching
 
04 spark-pair rdd-rdd-persistence
04 spark-pair rdd-rdd-persistence04 spark-pair rdd-rdd-persistence
04 spark-pair rdd-rdd-persistence
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Hash map
Hash mapHash map
Hash map
 
OLTP+OLAP=HTAP
 OLTP+OLAP=HTAP OLTP+OLAP=HTAP
OLTP+OLAP=HTAP
 
Apache HBase™
Apache HBase™Apache HBase™
Apache HBase™
 
Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0Programación Funcional 101 con Scala y ZIO 2.0
Programación Funcional 101 con Scala y ZIO 2.0
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 

Ähnlich wie Data Structures In Scala

lecture 11
lecture 11lecture 11
lecture 11
sajinsc
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
vanithasivdc
 

Ähnlich wie Data Structures In Scala (20)

CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Recursion Lecture in Java
Recursion Lecture in JavaRecursion Lecture in Java
Recursion Lecture in Java
 
R교육1
R교육1R교육1
R교육1
 
lecture 11
lecture 11lecture 11
lecture 11
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Zippers
ZippersZippers
Zippers
 
Soft Heaps
Soft HeapsSoft Heaps
Soft Heaps
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Bca ii dfs u-2 linklist,stack,queue
Bca ii  dfs u-2 linklist,stack,queueBca ii  dfs u-2 linklist,stack,queue
Bca ii dfs u-2 linklist,stack,queue
 
8.binry search tree
8.binry search tree8.binry search tree
8.binry search tree
 
8 chapter4 trees_bst
8 chapter4 trees_bst8 chapter4 trees_bst
8 chapter4 trees_bst
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Data structures
Data structures Data structures
Data structures
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Data Structures In Scala

  • 1. Data Structures In Scala Meetu Maltiar Principal Consultant Knoldus
  • 3. Functional Queue Functional Queue is a data structure that has three operations: head: returns first element of the Queue tail: returns a Queue without its Head enqueue: returns a new Queue with given element at Head Has therefore First In First Out (FIFO) property
  • 4. Functional Queue Continued scala> val q = scala.collection.immutable.Queue(1, 2, 3) q: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3) scala> val q1 = q enqueue 4 q1: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4) scala> q res3: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3) scala> q1 res4: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)
  • 5. Simple Queue Implementation class SlowAppendQueue[T](elems: List[T]) { def head = elems.head def tail = new SlowAppendQueue(elems.tail) def enqueue(x: T) = new SlowAppendQueue(elems ::: List(x)) } Head and tail operations are fast. Enqueue operation is slow as its performance is directly proportional to number of elements.
  • 6. Queue Optimizing Enqueue class SlowHeadQueue[T](smele: List[T]) { // smele is elems reversed def head = smele.last // Not efficient def tail = new SlowHeadQueue(smele.init) // Not efficient def enqueue(x: T) = new SlowHeadQueue(x :: smele) } smele is elems reversed. Head operation is not efficient. Neither is tail operation. As both last and init performance is directly proportional to number of elements in Queue
  • 7. Functional Queue class Queue[T](private val leading: List[T], private val trailing: List[T]) { private def mirror = if (leading.isEmpty) new Queue(trailing.reverse, Nil) else this def head = mirror.leading.head def tail = { val q = mirror new Queue(q.leading.tail, q.trailing) } def enqueue(x: T) = new Queue(leading, x :: trailing) }
  • 8. Binary Search Tree BST is organized tree. BST has nodes one of them is specified as Root node. Each node in BST has not more than two Children. Each Child is also a Sub-BST. Child is a leaf if it just has a root.
  • 9. Binary Search Property The keys in Binary Search Tree is stored to satisfy following property: Let x be a node in BST. If y is a node in left subtree of x Then Key[y] less than equal key[x] If y is a node in right subtree of x Then key[x] less than equal key[y]
  • 10. Binary Search Property The Key of the root is 6 The keys 2, 5 and 5 in left subtree is no larger than 6. The key 5 in root left child is no smaller than the key 2 in that node's left subtree and no larger than key 5 in the right sub tree
  • 11. Tree Scala Representation case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) This Tree representation is a recursive definition and has type parameterization and is covariant due to is [+T] signature This Tree class definition has following properties: 1. Tree has value of the given node 2. Tree has left sub-tree and it may have or do not contain value 3. Tree has right sub-tree and it may have or do not contain value It is covariant to allow subtypes to be contained in the Tree
  • 12. Tree In-order Traversal BST property enables us to print out all the Keys in a sorted order using simple recursive In-order traversal. It is called In-Order because it prints key of the root of a sub-tree between printing of the values in its left sub- tree and printing those in its right sub- tree
  • 13. Tree In-order Algorithm INORDER-TREE-WALK(x) 1. if x != Nil 2. INORDER-TREE-WALK(x.left) 3. println x.key 4. INORDER-TREE-WALK(x.right) For our BST in example before the output expected will be: 255678
  • 14. Tree In-order Scala def inOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => if (x.left != None) inOrder(x.left, f) f(x) if (x.right != None) inOrder(x.right, f) }
  • 15. Tree Pre-order Algorithm PREORDER-TREE-WALK(x) 1. if x != Nil 2. println x.key 3. PREORDER-TREE-WALK(x.left) 4. PREORDER-TREE-WALK(x.right) For our BST in example before the output expected will be: 652578
  • 16. Tree Pre-order Scala def preOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => f(x) if (x.left != None) inOrder(x.left, f) if (x.right != None) inOrder(x.right, f) } Pre-Order traversal is good for creating a copy of the Tree
  • 17. Tree Post-Order Algorithm POSTORDER-TREE-WALK(x) 1. if x != Nil 2. POSTORDER-TREE-WALK(x.left) 3. POSTORDER-TREE-WALK(x.right) 4. println x.key For our BST in example before the output expected will be: 255876 Useful in deleting a tree. In order to free up resources a node in the tree can only be deleted if all the children (left and right) are also deleted Post-Order does exactly that. It processes left and right sub-trees before processing current node
  • 18. Tree Post-order Scala def postOrder[A](t: Option[Tree[A]], f: Tree[A] => Unit): Unit = t match { case None => case Some(x) => if (x.left != None) postOrder(x.left, f) if (x.right != None) postOrder(x.right, f) f(x) }
  • 19. References 1. Cormen Introduction to Algorithms 2. Binary Search Trees Wikipedia 3. Martin Odersky “Programming In Scala” 4. Daniel spiewak talk “Extreme Cleverness: Functional Data Structures In Scala”