Preoder to BST construction - binary-search-tree

I am attempting to create a BST from an array of pre-order traversal. I wrote the following code, but can't figure out where am I making a mistake. The following code returns Nodes with values null. I am using the following approach:
10 8 4 5 14 12
I will partition it (after removing staring element):
8 4 5 and 14 12, (recursively).
public Node generateTree(int ar[], int low, int high) {
if (ar.length == 0 || low > high)
return null;
if (low == high)
return new Node(ar[low]);
int partitionPoint = findPartitionPoint(ar, low, high);
Node root = new Node(ar[low]);
if (partitionPoint != -1) {
root.left = generateTree(ar, low + 1, partitionPoint);
root.right = generateTree(ar, partitionPoint + 1, high);
} else {
root.left = generateTree(ar, low + 1, high);
}
return root;
}
private int findPartitionPoint(int ar[], int low, int high) {
if (high >= ar.length)
return -1;
for (int x = low; x <= high; x++) {
if (ar[x] > ar[low])
return x-1;
}
return -1;
}

I figured out the culprit. The issue was with Traversal function which I wrote separately. The Node function here takes int value, however, in Traversal function, I was printing its String value (my Node class has both String and Integer as keys). Such a silly mistake!
The code appears correct.

Related

Unable to display variable value in 16x2 LCD with Arduino

I am trying to get sensor input into my program and display it in a 16x2 LCD Display. I have two proximity sensors where the time difference between the two inputs is calculated and used in a formula. That value is applied to a variable and I want that value to be displayed in the LCD. It works fine with the Serial Monitor, but the values look Gibberish in the LCD.
I have changed the pin from 1 to 2 so that it is now "LiquidCrystal lcd(2, 3, 4, 5, 6, 7); ".
And now the sequence runs but no data is shown in the LCD. Maybe it is in loop and hence it is overwriting continuously. Is there a way to change the sequence so that the value comes only once and data shows in the LCD? (i.e, it is continuously providing output and if i try a while loop, it still shows nothing. Serial Monitor also goes empty.
Serial Monitor Image
LCD Display Image
Please find my code below and help me out with this issue.
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int limitSwitch = 13;
int limitSwitch2 = 12;
int state1 = LOW;
int state2 = LOW;
float centimeter = 0.050;
float timeRequired = 0.000;
float velocity = 0.000;
float durationFloat = 0.000;
unsigned long startTime;
unsigned long endTime;
unsigned long duration;
byte timerRunning;
void setup()
{
Serial.begin(9600);
lcd.begin(16,2);
pinMode(limitSwitch,INPUT);
pinMode(limitSwitch2,INPUT);
}
void loop()
{
int val1 = digitalRead(limitSwitch);
int val2 = digitalRead(limitSwitch2);
lcd.clear();
if( val1 != state1 || val2 != state2 )
{
state1 = val1;
state2 = val2;
if( state1 == 0 && timerRunning == 0 )
startTime = millis();
timerRunning = 1;
if( state2 == 0 && timerRunning == 1)
endTime = millis();
timerRunning = 0;
duration = endTime - startTime;
durationFloat = (float) duration;
timeRequired = durationFloat / 1000;
velocity = centimeter / timeRequired;
lcd.setCursor(0, 0);
lcd.print("Speed: ");
lcd.print(velocity);
lcd.setCursor(0, 1);
Serial.print("Speed in m/s = ");
Serial.println(velocity,7);
// lcd.print("Speed: "); lcd.print(velocity);
delay(1000);
}
}
it seems that you are using pin 1, but pin 0 and 1 in arduino are dedicated to the serial you are using

ffind leaf nodes of the binary search tree

i was asked in a interview question that given the preorder traversal of a binary search tree , find out the leaf nodes without constructing the original tree. i know the property that binary search tree has to satisfy but i cannot find any relation into how can it be done utilising this property . only thing i can identify is that the first node in th preorder traversal will be always be root. also google search did not yield any result for this problem. i do not want the code just a simple hint to begin with would be sufficient.
EDIT: after trying out a lot i got this solution:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void fl(vector<int> &v, int lo, int hi){
if (lo>hi) return;
if (lo == hi) { cout<<"leaf ^^^^^^^ "<< v[hi]<<"\n"; return; }
int root = v[lo];
int i;
for(i = lo+1 ; i <= hi ; i++) if (v[i] > root) break;
fl(v, lo+1, i -1);
fl(v, i , hi);
}
int main(){
vector<int> v1 = {8, 3, 1, 6, 4, 7, 10, 14, 13};
vector<int> v2 = {27, 14, 10, 19, 35, 31, 42};
vector<int> v3 = {9,8,7,6,5,4,3,2,1};
fl(v3,0,v3.size()-1);
return 0;
}
any suggestions for improvement other than variable names will be very helpful
This program should print the leaf nodes from a preOrder of BST. The program is pretty self explanatory.
public static void findLeafs(int[] arr) {
if (arr == null || arr.length == 0)
return;
Stack<Integer> stack = new Stack<>();
for(int n = 1, c = 0; n < arr.length; n++, c++) {
if (arr[c] > arr[n]) {
stack.push(arr[c]);
} else {
boolean found = false;
while(!stack.isEmpty()) {
if (arr[n] > stack.peek()) {
stack.pop();
found = true;
} else
break;
}
if (found)
System.out.println(arr[c]);
}
}
System.out.println(arr[arr.length-1]);
}
def getLeafNodes(data):
if data:
root=data[0]
leafNodes=[]
process(data[1:],root,leafNodes)
return leafNodes
def process(data,root,leafNodes):
if data:
left=[]
right=[]
for i in range(len(data)):
if data[i]<root:
left.append(data[i])
if data[i]>root:
right.append(data[i])
if len(left)==0 and len(right)==0:
leafNodes.append(root)
return
if len(left)>0:
process(left[1:],left[0],leafNodes)
if len(right)>0:
process(right[1:],right[0],leafNodes)
else:
leafNodes.append(root)
#--Run--
print getLeafNodes([890,325,290,530,965])

Time/Space-Complexity method

I got a question to answer with the best complexity we can think about.
We got one sorted array (int) and X value. All we need to do is to find how many places in the array equals the X value.
This is my solution to this situation, as i don't know much about complexity.
All i know is that better methods are without for loops :X
class Question
{
public static int mount (int [] a, int x)
{
int first=0, last=a.length-1, count=0, pointer=0;
boolean found=false, finish=false;
if (x < a[0] || x > a[a.length-1])
return 0;
while (! found) **//Searching any place in the array that equals to x value;**
{
if ( a[(first+last)/2] > x)
last = (first+last)/2;
else if ( a[(first+last)/2] < x)
first = (first+last)/2;
else
{
pointer = (first+last)/2;
count = 1;
found = true; break;
}
if (Math.abs(last-first) == 1)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else if (a[last] == x)
{
pointer = last;
count = 1;
found = true;
}
else
return 0;
}
if (first == last)
{
if (a[first] == x)
{
pointer = first;
count = 1;
found = true;
}
else
return 0;
}
}
int backPointer=pointer, forwardPointer=pointer;
boolean stop1=false, stop2= false;
while (!finish) **//Counting the number of places the X value is near our pointer.**
{
if (backPointer-1 >= 0)
if (a[backPointer-1] == x)
{
count++;
backPointer--;
}
else
stop1 = true;
if (forwardPointer+1 <= a.length-1)
if (a[forwardPointer+1] == x)
{
count++;
forwardPointer++;
}
else
stop2 = true;
if (stop1 && stop2)
finish=true;
}
return count;
}
public static void main (String [] args)
{
int [] a = {-25,0,5,11,11,99};
System.out.println(mount(a, 11));
}
}
The print command count it right and prints "2".
I just want to know if anyone can think about better complexity for this method.
Moreover, how can i know what is the time/space-complexity of the method?
All i know about time/space-complexity is that for loop is O(n). I don't know how to calculate my method complexity.
Thank a lot!
Editing:
This is the second while loop after changing:
while (!stop1 || !stop2) //Counting the number of places the X value is near our pointer.
{
if (!stop1)
{
if ( a[last] == x )
{
stop1 = true;
count += (last-pointer);
}
else if ( a[(last+forwardPointer)/2] == x )
{
if (last-forwardPointer == 1)
{
stop1 = true;
count += (forwardPointer-pointer);
}
else
forwardPointer = (last + forwardPointer) / 2;
}
else
last = ((last + forwardPointer) / 2) - 1;
}
if (!stop2)
{
if (a[first] == x)
{
stop2 = true;
count += (pointer - first);
}
else if ( a[(first+backPointer)/2] == x )
{
if (backPointer - first == 1)
{
stop2 = true;
count += (pointer-backPointer);
}
else
backPointer = (first + backPointer) / 2;
}
else
first = ((first + backPointer) / 2) + 1;
}
}
What do you think about the changing? I think it would change the time complexity to O(long(n)).
First let's examine your code:
The code could be heavily refactored and cleaned (which would also result in more efficient implementation, yet without improving time or space complexity), but the algorithm itself is pretty good.
What it does is use standard binary search to find an item with the required value, then scans to the back and to the front to find all other occurrences of the value.
In terms of time complexity, the algorithm is O(N). The worst case is when the entire array is the same value and you end up iterating all of it in the 2nd phase (the binary search will only take 1 iteration). Space complexity is O(1). The memory usage (space) is unaffected by growth in input size.
You could improve the worst case time complexity if you keep using binary search on the 2 sub-arrays (back & front) and increase the "match range" logarithmically this way. The time complexity will become O(log(N)). Space complexity will remain O(1) for the same reason as before.
However, the average complexity for a real-world scenario (where the array contains various values) would be very close and might even lean towards your own version.

How to print out the digits of an integer of any length?

This program is works as long as the divide variable is of the same base 10 power as the variable num, in this case the number is 12345 so divide needs to be 10000. While this works for 5 digit numbers, anything with more or less than 5 digits will not have their individual digits printed out. How do I configure divide to have be of the same base 10 power as num automatically?
public class lab5testing
{
public static void main (String args[])
{
int num = 12345, digit = 0, divide = 10000;
if (num != 0)
{
while(num != 0 )
{
digit = ((num/divide)%10);
System.out.println(digit);
divide /= 10;
if (divide == 0)
{
num = 0;
}
}
}
else
{
System.out.println(num);
}
}
}
Maybe you should try with this :
int length = (int)(Math.log10(num)+1);
and then :
int divide = Math.pow(10,lengh);

How to increase an ipv6 address based on mask in java?

i am trying to increment ipv6 address based on mask.
i am getting problem when there is F in place of increment.
could any one plz check this
public String IncrementIPV6ForPrefixLength (String IPv6String, int times) throws UnknownHostException
{
int result , carry = 0, i;
int bits;
int mask=0;
int index=IPv6String.indexOf("/");
mask=Integer.parseInt(IPv6String.substring(index+1, IPv6String.length()));
IPv6String=IPv6String.substring(0, index);
InetAddress iaddr=InetAddress.getByName(IPv6String);
byte[] IPv6Arr=iaddr.getAddress();
if(mask > 128 || mask < 0)
return null;
i = mask/8;
bits = mask%8;
if(bits>0)
{
result = ((int)(IPv6Arr[i]>>(8-bits))) + times;
IPv6Arr[i] =(byte) ((result << (8-bits)) | (IPv6Arr[i] & (0xff >> (bits))));
carry = (result << (8-bits))/256;
times /= 256;
}
i--;
for(;i>=0;i--)
{
result = ((int)IPv6Arr[i]) + ((times + carry)& 0xFF);
IPv6Arr[i] = (byte)(result % 256);
carry = result / 256;
if(carry == 0)
{
iaddr=InetAddress.getByAddress(IPv6Arr);
String s=iaddr.toString();
if(s.indexOf('/') != -1){
s = s.substring(1, s.length()).toUpperCase();
}
StringBuffer buff =new StringBuffer("");
String[] ss = s.split(":");
for(int k=0;k<ss.length;k++){
int Differ = 4 - ss[k].length();
for(int j = 0; j<Differ;j++){
buff.append("0");
}
buff.append(ss[k]);
if(k!=7)buff=buff.append(":");
}
return buff.toString()+"/"+mask;
}
times /= 256;
}
return null;
}
input like this:
FD34:4FB7:FFFF:A13F:1325:2252:1525:325F/48
FD34:41B7:FFFF::/48
FD34:4FBF:F400:A13E:1325:2252:1525:3256/35
output like this
if increment by 1
FD34:4FB8:0000:A13F:1325:2252:1525:325F/48
FD34:41B8:0000::/48
FD34:4FC0:0400:A13E:1325:2252:1525:3256/35
if increment by 2
FD34:4FB8:0001:A13F:1325:2252:1525:325F/48
FD34:41B8:0001::/48
FD34:4FC0:1400:A13E:1325:2252:1525:3256/35
can u plz find where i am doing wrong.
Disregarding the posted code, try to model the operation as a direct numerical operation on the 128-bit number that the IPv6 address really is. Convert to BigInteger and use BigInteger.add.