So this is my first java program, but I've done c++ for a few years. I wrote what I think should work, but in fact it does not. So I had a stipulation of having to write a method for this call:

```
tree.insertNode(value);
```

where value is an int. I wanted to write it recursively, for obvious reasons, so I had to do a work around:

```
public void insertNode(int key) {
Node temp = new Node(key);
if(root == null) root = temp;
else insertNode(temp);
}
public void insertNode(Node temp) {
if(root == null)
root = temp;
else if(temp.getKey() <= root.getKey())
insertNode(root.getLeft());
else insertNode(root.getRight());
}
```

Thanks for any advice.

You can use standard `Integer`

(wrapper for primitive int) object instead of creating a new object type `Node`

. On latest java Integer/int **auto-boxing** is supported. Hence your method `insertNode(int key)`

can take in `Integer`

argument too (ensure it is not null).

EDIT: Pls ignore above comment. I did not understand your real question. You will have to overload `insertNode()`

. I think you are right.

but where is temp when you `insertNode`

?? With your current implementation temp is lost if root is not null.

I think you want something like

```
root.getLeft().insertNode(temp);
```

and

```
root.getRight().insertNode(temp);
```

i.e. To insert the new Node (temp) to either the left or the right subtree.

The code looks a little confusing with overloaded functions. Assuming member variables 'left' and 'right' to be the left child and right child of the BSTree respectively, you can try implementing it in the following way:

```
public void insert(Node node, int value) {
if (value < node.value)
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
node.left = new Node(value);
}
}
else if (value > node.value)
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
node.right = new Node(value);
}
}
}
........
public static void main(String [] args)
{
BSTree bt = new BSTree();
Node root = new Node(100);
bt.insert(root, 50);
bt.insert(root, 150);
}
```

```
//In java it is little trickier as objects are passed by copy.
//PF my answer below.
//public calling method
public void insertNode(int key) {
root = insertNode(root, new Node(key));
}
//private recursive call
private Node insertNode(Node currentParent, Node newNode) {
if (currentParent == null)
return newNode;
else if (newNode.key > currentParent.key)
currentParent.right = insertNode(currentParent.right, newNode);
else if (newNode.key < currentParent.key)
currentParent.left = insertNode(currentParent.left, newNode);
return currentParent;
}
```

**Sameer Sukumaran**

You should have a look to this article. It helps to implement a tree structure and search, insert methods: http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

```
// This method mainly calls insertRec()
void insert(int key) {
root = insertRec(root, key);
}
/* A recursive function to insert a new key in BST */
Node insertRec(Node root, int key) {
/* If the tree is empty, return a new node */
if (root == null) {
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
```

Similar Questions

want to insert element in binary tree. what is wrong in this code. I have a structure with data, left and right as self referencing structure and root as a global variable of type structure initialize

We all know that a hash table has O(1) time for both inserts and look-ups if the hash function was well chosen. So, what are the reason we want to use Binary Search Tree? Just because a perfect hash f

having a bit of problems with my insert function here. It compiles fine but if I try to add a 4th node it just replaces one of the first child nodes instead of adding a new one to those child nodes..

I am still fairly new to generics and binary search trees, and I am trying to add a custom Student object to a BST, and don't know exactly how to go about implementing it. I have my Student class decl

I am trying to change my recursive insert method of the BST into non-recursive( maybe While loop) The reason for this changing because I want to see if it is possible. Here is the code of insertion: p

I am trying to make a binary search tree, but when I try to insert any value, or more precisely when a NULL pointer gets passed to the function, it just freezes for a little while and then it crashes.

Basic Tree-search algorithm for searching a node (with value k) in a binary search tree. 'x' denotes the node of the binary search tree. TREE-SEARCH (x, k) if x= NIL or k = key[x] then return x if k &

I want to implement an algorithm that inserts sorted arrays into binary search trees but I don't want ending up with a tree that only grows to one side. Do you have any ideas? Thanks.

Why do people use binary search trees? Why not simply do a binary search on the array sorted from lowest to highest? To me, an insertion / deletion cost seems to be the same, why complicate life with

I have a working search function that will search for the exact value in a database, but my goal is for it to search for substrings in the database of the stored data and when searching for substrings

I am new to data structures and binary trees so I am a little bit lost . My problem is that how do we insert values in the tree itself ?

I am writing a function that will remove an entry from a binary search tree that has a given key associated with it. So far I have this for my code: template <typename Item, typename Key = Item>

I have problem with method MoveNext in my enumerator. I need iterator for binary search tree. In construcotr of my enumerator I initialize Node to root of tree. Current is value that I ened to return

I am developing a binary search tree in java. But i am facing certain difficulties in it. Here is the code class Node { Node left, right; Integer data; Node(Integer d, Node left, Node right) { this.da

Trying to make a contains function for a binary tree. The function looks like this: bool contains(bt_node* top, int data) { if (top == NULL) return false; else { if (data == top->data) return true

Suppose I have a list of strings and a prefix tree of those strings, and I would like to locate a string given a key, which one is more faster? binary search or prefix tree search? Why and what's the

I want to implement a generic type binary search tree. The declarations are as follow: public BTNode<T> {} public class BinaryTree<T extends Comparable<T>> {} public class BinarySear

I need to create a function that creates a BST from an array, in python. The array is already sorted. The example is: function array_to_binary_search_tree(array, start, end) if start > end Return a

I am doing homework and I am try to implement some binary search tree functions. I am also very new to programming, and do not have much experience with programming. I have the functions written out,

I'm studying Java data structures and algorithms in college and we have come across the topic of binary search trees and tree transversal but I don't see the purpose of these topics in my programming.

I'm trying to find and fix what is wrong with this code. It's a binary search implemented by recursion. I dont know why it's returning stack overflow and crashing. bool find( const int x, const int* p

Functions in scheme/racket. Working on a few functions using a binary search tree. I have already defined helper functions to be: ;; returns value of node (define (value node) (if (null? node) '() (ca

Binary search tree algorithms usually uses recursion and i m having hard time with recursion. This is a code which converts the tree into its mirror image . void mirror_image(struct tree* node1) { if

As mentioned in the Title , I have a Binary search tree. I want to convert it to sorted doubly linklist using recursion. My code for each node in tree find max of left sub-tree and assign its right t

I wrote an insert method for a binary search tree that is void. I have to change that method so that it returns a boolean but I am confused because my helper method for insert returns a Node. Is there

Why is the worst case big-O for inserting N items into an empty binary search tree n^2? there are no balance checks.

template <class T> void BinaryTree<T>::LoadTree(const char *file) { ifstream fin; fin.open(file); string buffer; T buff; while (!fin.eof()) { getline(fin,buffer,'~'); fin>>buff; Tree

I'm writing a program that takes input from a txt file then inputs it into a BST (then manipulates the data, etc.) What's happening is the data file is read properly, it goes to the Insert function,

When running this program I add about 3 or 4 values into the binary search tree. After adding the values in the tree I use the check balance method to see if the inbalance is 2 or greater. Once it is

I'm doing a small Java work on Binary Search Tree but when I'm implementing the recursive insert of a node into the tree and display it, I don't get anything. I've been on it for a while now, I don't

I am studying Breadth First Search , and wanted to ask that Is the Tree constructed by Breadth First Search ( the BFS tree, wherein we store each node's predecessor) a Binary Tree?

I need help with a binary search tree. Here are the node and BST classes : public class Node { private int key; private Node parent; private Node leftChild; private Node rightChild; public Node(int ke

What's the best way to create a balanced binary search tree from a sorted singly linked list?

I am trying to create a program which which takes a list of words as an input, and sorts them into a binary tree, in order to allow them to be found, e.g. like a dictionary. This is what I have done s

I was trying out an iterative method to find the height/depth of a binary search tree. Basically, I tried using Breadth First Search to calculate the depth, by using a Queue to store the tree nodes an

I'm working with deleting nodes from a binary search tree and I keep getting a segfault error after the while loop in this function. Please help me catch any errors if you can. Thanks! Here is the fun

I am implementing a Binary Search tree in C++ I have the following code to add an entry to the tree: void tree::add(int n) { int found; leaf *t,*parent; findparent(n,found,parent); if(found==YES) cout

I'm trying to make a search method using a binary tree(no, it's not a binary search tree, just a binary tree) using a recursive function. If the data is on the binary tree, i want it to return the nod

I need to build a balanced binary search tree. So far my program inserts the numbers from 1 to 26, but my program does not build it into a balanced binary search tree. If anyone could look at my code

I need help in 3 tasks. I'm really new in Haskell and functional programming. data Tree = Node Int Tree Tree | Nil Define with help of the function collapse collapse :: Tree -> [Int] collapse N

I am working on a template for a binary search tree and I am getting the error below. I know there are similar post but I can't figure this thing out. Templates are definitely a weak subject for me so

I want to find the max depth of binary search tree. I found a code. int maxDepth(struct node* node) { if (node==NULL) { return(0); } else { // compute the depth of each subtree int lDepth = maxDepth(n

I found a lot of source codes on how to add element to a binary search tree, but I wasn't able to find illustration of adding an element to a binary search tree in a diagram form. For example if I wa

I'm implementing the insert function of a BST, below is my code: data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq) tinsert :: Tree a -> a -> Tree a tinsert Empty a = Branch a

I have written such the code below that ; I have an array list which has 3 objects . each object has 2 fields 1)digit2)level I want to insert each object to a binary search tree and after inserting ea

I have a problem with finding the second maximum element in a binary search tree. I do not know why but in some cases my programm crashes or gives incorrect answer (I don't know those cases). Help me

I'm using a binary search tree that collects strings and then orders them in post order. I also use a list that shows the line number where the string appears. I can make the BST work properly however

so I have been trying to get an old c++ binary search tree program of mine to work.It compiles and runs but I do not get the results I would expect. If I insert c,d,a,b in that order and try to remove

I'm currently trying to implement an immutable BST in clojure. This is my make-tree function: (defn make-tree [v] {:v v :l nil :r nil}) and insertion: (defn insert [tree v] (if (nil? tree) (make-tree

i am having a normal binary tree that i am trying to apply iterative deepening depth first search on using c : struct node { int data; struct node * right; struct node * left; }; typedef struct node n