Recursive to Iterative method for Binary Search Tree - recursion

I'm working on an assignment to get the height of the BST using an iterative method from an recursive method. Below will be the provided recursive code and my code. It is returning one greater than the actual height. For example, the height is suppose to be 4, but it returns 5.
//Provided code
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node==null) {
return -1;
} else {
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
//my code
public int getHeightI() {
return getHeightI(root);
}
private int getHeightI(Node node) {
Node curr = node;
int leftHeight = 0;
int rightHeight = 0;
if (curr!=null) {
while (curr.left!=null) {
leftHeight++;
curr = curr.left;
}
while (curr.right!=null) {
rightHeight++;
curr = curr.right;
}
}
return Math.max(leftHeight, rightHeight)+1;
}

Your Code is returning one more than actual height of Tree. I suggest you to use this code
int height(tree* root)
{
if(!root)
{ return -1;
}
else{
return __max(root->left,root->right);
}
Hope you understand your mistake.

Related

How do I periodically append to an array using the Arduino IDE?

I am trying to append float values that the user inputs through the serial monitor. I need these values stored in an array in a sequential fashion, i.e. each time I get a value, I must append it to the array.
Arduino doesn't come out of the box with dynamic data structures (except for String).
You can download open source implementations of generic containers from the web. Here's one: https://github.com/dhbikoff/Generic-C-Library/blob/master/vector.h
Also, here's a simple linked-list/vector I implemented myself as a toy project.
Be careful with dynamic memory. Memory fragmentation can cause your sketch to crash randomly (has happened to me several times).
template <typename T>
struct SimpleVector {
struct SimpleVectorNode {
T* m_value = NULL;
SimpleVectorNode* m_next = NULL;
SimpleVectorNode() {
}
SimpleVectorNode(T val) {
m_value = new T(val);
m_next = NULL;
}
};
int m_size = 0;
SimpleVectorNode* m_head = new SimpleVectorNode;
void AddValue(T val) {
++m_size;
SimpleVectorNode* end = m_head;
while (end->m_next != NULL) {
end = end->m_next;
}
end->m_next = new SimpleVectorNode(val);
}
SimpleVectorNode* Seek(int index) {
SimpleVectorNode* res = m_head;
while (index >= 0) {
--index;
res = res->m_next;
}
return res;
}
T& Get(int index) {
return *(Seek(index)->m_value);
}
void Delete(int index) {
SimpleVectorNode* preDel = Seek(index - 1);
SimpleVectorNode* toDel = preDel->m_next;
preDel->m_next = toDel->m_next;
delete toDel->m_value;
delete toDel;
--m_size;
}
int GetSize() {
return m_size;
}
int IndexOf(T val) {
SimpleVectorNode* pNode = m_head->m_next;
for (int i = 0; i < m_size; ++i) {
if (pNode->m_value == val) {
return i;
}
pNode = pNode->m_next;
}
return -1;
}
bool Contains(T val) {
return IndexOf(val) >= 0;
}
~SimpleVector() {
while (m_size > 0) {
Delete(0);
}
delete m_head;
}
};

How to use prefix tree data structure

I have a smg file that contains different articles. Now I would like to use prefix tree data structure to establish baseline word counts for the entire corpus of documents. A sample of the file can be found below:
<REUTERS TOPICS="YES" LEWISSPLIT="TRAIN" CGISPLIT="TRAINING-SET"
OLDID="5544" NEWID="1">
<DATE>26-FEB-1987 15:01:01.79</DATE>
<TOPICS><D>cocoa</D></TOPICS>
<PLACES><D>el-salvador</D><D>usa</D><D>uruguay</D></PLACES>
<PEOPLE></PEOPLE>
<ORGS></ORGS>
<EXCHANGES></EXCHANGES>
<COMPANIES></COMPANIES>
<UNKNOWN>
C T
f0704reute
u f BC-BAHIA-COCOA-REVIEW 02-26 0105</UNKNOWN>
<TEXT>
<TITLE>BAHIA COCOA REVIEW</TITLE>
<DATELINE> SALVADOR, Feb 26 - </DATELINE><BODY>
Some text here.
Reuter
</BODY></TEXT>
</REUTERS>
Any advice on how to establish the baseline word counts?
use trie data structure to load strings and retrieve suggestions faster
public class Trie
{
public struct Letter
{
public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static implicit operator Letter(char c)
{
c = c.ToString().ToUpper().ToCharArray().First();
return new Letter() { Index = Chars.IndexOf(c) };
}
public int Index;
public char ToChar()
{
return Chars[Index];
}
public override string ToString()
{
return Chars[Index].ToString();
}
}
public class Node
{
public string Word;
public bool IsTerminal { get { return Word != null; } }
public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
}
public Node Root = new Node();
public Trie(string[] words)
{
for (int w = 0; w < words.Length; w++)
{
var word = words[w];
var node = Root;
for (int len = 1; len <= word.Length; len++)
{
var letter = word[len - 1];
Node next;
if (!node.Edges.TryGetValue(letter, out next))
{
next = new Node();
if (len == word.Length)
{
next.Word = word;
}
node.Edges.Add(letter, next);
}
node = next;
}
}
}
public List<string> GetSuggestions(string word, int max)
{
List<string> outPut = new List<string>();
var node = Root;
int i = 0;
foreach (var l in word)
{
Node cNode;
if (node.Edges.TryGetValue(l, out cNode))
{
node = cNode;
}
else
{
if (i == word.Length - 1)
return outPut;
}
i++;
}
GetChildWords(node, ref outPut, max);
return outPut;
}
public void GetChildWords(Node n, ref List<string> outWords, int Max)
{
if (n.IsTerminal && outWords.Count < Max)
outWords.Add(n.Word);
foreach (var item in n.Edges)
{
GetChildWords(item.Value, ref outWords, Max);
}
}
}

Sequence 1, 3, 8, 18, 38, 78 from a recursive function

I'm trying to write a recursive function in Java that would display the n element in a mathematical number sequence (1 3 8 18 38 78).
This is what I've managed to do so far:
public static int recfunc(int i) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1); }
if(i==3) { return 5+recfunc(i-1); }
if(i>3) { return ((2^(i-3))*5)+recfunc(3); }
return 0;
}
To calculate n(>3), you simply add together 2^(i-3) from each step(i>3) and then add 8 in the end. So, for the 6th element, you would have to do this calculation: 40 + 20 + 10 + 8 = 78.
The problem with the above code is that it successfully calculates the increase in a number between two n(s) and then ads 5 + 2 + 1 (8) to it, but it doesn't apply all the previous steps (20 + 10).
Update:
I'm getting somewhere, but it still doesn't do what it should.
public static int recfunc(int i, boolean param) {
if(param==false) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1, false); }
if(i==3) { return 5+recfunc(i-1, false); }
if(i>3) { param = true; }
}
if(param==true) {
if(i==4) {
return ((2^(i-3))*5)+recfunc(i-1, false); }
else {
return ((2^(i-3))*5)+recfunc(i-1, true); }
}
return 0;
}
The problem is with your power function. ^ in java does not mean to raise to a power. It means XOR.
You can use java's Math.pow()
int recfunc(int i) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1); }
if(i==3) { return 5+recfunc(i-1); }
if(i>3) {
return ((Math.pow(2,(i-3))*5)+recfunc(i-1));
}
return 0;
}
Hope this helps.
This code works fine now. Thanks for your help!
public static int recfunc(int i, boolean param) {
if(param==false) {
if(i==1) { return 1; }
if(i==2) { return 2+recfunc(i-1, false); }
if(i==3) { return 5+recfunc(i-1, false); }
if(i>3) { param = true; }
}
if(param==true) {
if(i==4) {
return (int)Math.pow(2.0f,(double)(i-3))*5+(int)(recfunc(i-1, false)); }
else {
return (int)Math.pow(2.0f,(double)(i-3))*5+(int)(recfunc(i-1, true)); }
}
return 0;
}

Binary Search Tree implemented in Java - Find Element recursively

Using Java, is it possible to write a recursive method to find an element in a binary search tree? I say no because of the nature of recursive re-tracing back unless I implemented incorrectly? I have been searching the internet and all i can find is an iterative version. Here is my method:
public boolean findValueRecursively(BSTNode node, int value){
boolean isFound = false;
BSTNode currentNode = node;
if (value == currentNode.getData()){
isFound = true;
return isFound;
} else if (value < currentNode.getData()){
findValueRecursively(currentNode.getLeftNode(), value);
} else{
findValueRecursively(currentNode.getRightNode(), value);
}
return isFound;
}
// Node data structure
public class BSTNode
{
private BSTNode leftNode;
private BSTNode rightNode;
private int data;
public BSTNode(int value, BSTNode left, BSTNode right){
this.leftNode = left;
this.rightNode = right;
this.data = value;
}
}
public static void main(String[] args){
BST bst = new BST();
// initialize the root node
BSTNode bstNode = new BSTNode(4, null, null);
bst.insert(bstNode, 2);
bst.insert(bstNode, 5);
bst.insert(bstNode, 6);
bst.insert(bstNode, 1);
bst.insert(bstNode, 3);
bst.insert(bstNode, 7);
if (bst.findValueRecursively(bstNode, 7)){
System.out.println("element is found! ");
} else{
System.out.println("element is not found!");
}
}
I get the print as "element is not found".
Any help/tips or suggestions, more than welcome.
Thanks in advance!
A recursive version:
public boolean findValueRecursively(Node node, int value){
if(node == null) return false;
return
node.data == value ||
findValueRecursively(leftNode, value) ||
findValueRecursively(rightNode, value);
}
A recursive version that returns a reference to the node found:
public BinaryNode find(BinaryNode node, int value) {
// Finds the node that contains the value and returns a reference to the node.
// Returns null if value does not exist in the tree.
if (node == null) return null;
if (node.data == value) {
return node;
} else {
BinaryNode left = find(node.leftChild, value);
BinaryNode right = find(node.rightChild, value);
if (left != null) {
return left;
}else {
return right;
}
}
}
I believe your isFound = false; is what is always getting returned.
It should be like this:
isFound= findValueRecursively(currentNode.getLeftNode(), value);
public TreeNode<E> binarySearchTree(TreeNode<E> node, E data){
if(node != null) {
int side = node.getData().compareTo(data);
if(side == 0) return node;
else if(side < 0) return binarySearchTree(node.getRightChild(), data);
else if(side > 0 ) return binarySearchTree(node.getLeftChild(), data);
}
return null;
}
That will return a reference to the node, which is a little more useful IRL. You can change it to return a boolean though.

It throws an stackoverflow exception when I user PropertyInfo.SetValue()

When I use PropertyInfo.SetValue in asp.net , it throws a stackoverflow exception.
That I write this code:
for (int i = 0; i < rivalSeriesIDList.Count; i++)
{
cardb_series rivalSeries = seriesBll.GetSeriesInfoByID(rivalSeriesIDList[i].ToString());
this.GetType().GetProperty("brandid" + (i + 1)).SetValue(this, rivalSeries.brand_id, null);
this.GetType().GetProperty("seriesid" + (i + 1)).SetValue(this, rivalSeries.series_id, null);
}
And brandid+number and seriesid+number is a property of aspx_page. like this:
public int brandid1
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
brandid1 = value;
}
}
when I test the code in a Console Application ,It is all right . But when I test it in a Web Application ,it will cause a stack overflow exception .
I don't know why. Because of web is no-state?
Thanks.
cause you call your property recursively, and will get the same exception even if you will call the property directly
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
and this one -> brandid1 = value;
}
}
I don't know what do you want to do, but try this
private int _brandid1;
public int brandid1 <- this one
{
get
{
if (Request.Form["brandid1"] != null)
return int.Parse(Request.Form["brandid1"]);
if (Request["brandid1"] != null)
return int.Parse(Request["brandid1"]);
return 0;
}
set
{
_brandid1 = value;
}
}

Resources