Insertion of nodes into BST with Scala

Kumar Nellipudi
2 min readMar 7, 2022

Design a case class in such a way that it accepts optional left, right nodes

case class Node(value: Int, left: Option[Node], right: Option[Node])

Write a recursive definition which accepts key & tree; returns optional node

def insert(element: Int, tree: Option[Node]): Option[Node] = tree match {
case Some(subtree) => if(element > subtree.value)
subtree.right(copy = insert(element, subtree.right)) else
subtree.left(copy=insert(element, subtree.left)
case None => Some(Node(element, None, None))
}

FInally we have our own list or set to pass for insertion

val x= List(10, 6, 7,15, 8, 4, 9, 24, 60, 71).toSet.toList

Self note: Have an illustration image here: (use draw.io)

x.tail.foldLeft(Some(Node(x.head, None, None)((m,n) => insert(n,m))

Verification of BST insertion / Search within BST

PLEASE DO NOT READ THIS: its written for mock interview with peer. (java solution for simple regex validator)
import java.io.*;
import java.util.*;

class Solution {

static boolean isMatch(String text, String pattern) {
// your code goes here
Stack<Character> s = new Stack<>();
char[] words = text.toCharArray();
char[] pwords = pattern.toCharArray();
for(char x: pwords) s.push((Character)x);
boolean isMatch = true;
int i = 0;
char curr = ‘\0’;
for(i = text.length()-1; i>=0 || !s.isEmpty(); i — ) {
if(!s.isEmpty()) curr = s.peek(); else break;
char carry;
if(curr == ‘.’) {
s.pop();
//if(s.peek() == ‘.’ || s.peek() == ‘*’) {isMatch = false; break;}
continue;
}
else if(curr == ‘*’){s.pop(); carry = s.pop(); if(carry == ‘*’){isMatch = false; break;} else if(carry == ‘.’) continue; else {while(i>=0 && (carry == words[i]) ) i — ; if(!s.isEmpty()){i++;}};}
else if(words[i] == curr && isMatch) {s.pop();continue;}
else {isMatch = false; break;}
}
if(i>=0 || !s.isEmpty()) {isMatch = false;}
return isMatch;
}

public static void main(String[] args) {

}

}

--

--

Kumar Nellipudi

Exploring emerging technologies, Exploring problem solving