Insert in binary tree using recursion - java

I am trying to implement binary tree NOT binary search tree. I spent a good amount of time to write insert operation using recursion but did not get.
It should be a complete tree that is filling from left to right.
Can someone help me with that?Preferably in Java.
The following is the iterative way to do it .(:( this is not even working))
public static void insertNode(Node root,int x){
if(root==null) {
root = new Node(x);
return;
}
Node current;
Queue<Node> qq = new LinkedList<Node>();
((LinkedList<Node>) qq).push(root);
while(true){
current=qq.peek();
if(current.leftchild==null){
Node child = new Node(x);
child.parent = current;
current.leftchild=child;
return;
}
else { ((LinkedList<Node>) qq).push(current.leftchild);}
if(current.rightChild==null){
Node child = new Node(x);
child.parent=current;
current.rightChild=child;
return;
}
else{
((LinkedList<Node>) qq).push(current.rightChild);
}
((LinkedList<Node>) qq).pop();
}

The problem with your code is that you are pushing into the Linked List when actually you want to add to the list.
LinkedList.push(element) adds element to the front of the list while the LinkedList.add(element) will add element to the end. Following is the correct snippet:
public static void insertNode(Node root,int x){
{
if(root==null) {
root = new Node(x);
return;
}
Node current;
Queue<Node> qq = new LinkedList<Node>();
((LinkedList<Node>) qq).push(root);
while(true){
current=qq.peek();
if(current.leftchild==null){
Node child = new Node(x);
child.parent = current;
current.leftchild=child;
return;
}
else {
((LinkedList<Node>) qq).add(current.leftchild);}
if(current.rightChild==null){
Node child = new Node(x);
child.parent=current;
current.rightChild=child;
return;
}
else{
((LinkedList<Node>) qq).add(current.rightChild);
}
((LinkedList<Node>) qq).pop();
}
}

Related

How to update the nodes in the hash Map in specific key in java?

I want to remove all even nodes from the linked list. How can I update the node in the specific key of the hashmap? H.get(0).next=temp is not working. The desired output is 2 4, but I'm not getting it.
public static void main(String[] args) {
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
Node temp=head;
HashMap<Integer,Node>H=new HashMap<>();
while(temp!=null) {
if(temp.data%2==0) {
if(!H.containsKey(0)) {
H.put(0, temp);
} else {
//This statement is not working
H.get(0).next=temp;
}
}
temp=temp.next;
}
head=H.get(0);
while(temp!=null) {
System.out.print(temp.data);
temp=temp.next;
}
}
}
In the last loop, you wrote while(temp!=null){ but the temp is null after the loop and doesn't reference the head.
I don't see the value in using HashMap here.
Here's what we can do to remove all nodes with even data:
Node head;
head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
Node oddTail = null, curr = head;
while (curr != null) {
if (curr.data % 2 != 0) { // Odd data
if(oddTail != null){
oddTail.next = curr; // Update oddTail
}
oddTail = curr;
}
curr = curr.next;
}
if(oddTail != null){ // The oddTail.next might point to a node with even data
oddTail.next = null;
} else{
head = null; // No nodes with odd data
}
curr = head;
// Print the list
while(curr != null){
System.out.println(curr.data);
curr = curr.next;
}
Output:
1
3
5
Normally you don't need a HashMap when doing operations on a Linked List, you just have to keep the reference of the nodes and remove them accordingly.
I think something like this should work.
As you see I don't have the referenced stored in a HashMap but what I try to do is to explore from the head to the tail, keeping a reference of the previous node I explored. Why? Because when I find an even node I want to be connect the previous node to the next one such that I remove the current node. I have the edge case of when the even node is the head because there is no previous node assigned.
Wasn't really able to try this code but maybe works as a reference for what you're trying to do.
public static void main(String[] args) {
head=new Node(1);
head.next=new Node(2);
head.next.next=new Node(3);
head.next.next.next=new Node(4);
head.next.next.next.next=new Node(5);
Node current = head;
Node prev = null;
while(current != null){
if(current.data%2==0){
if(current == head){
head = current.next;
} else {
prev.next = current.next;
current = current.next;
}
} else {
prev = current;
current = current.next;
}
}
current = head
while(current!=null){
System.out.print(current.data);
current=current.next;
}
}

write a function to add to the end of linked list [duplicate]

I'm studying for an exam, and this is a problem from an old test:
We have a singly linked list with a list head with the following declaration:
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d;
next = n;
}
}
Write a method void addLast(Node header, Object x) that adds x at the end of the list.
I know that if I actually had something like:
LinkedList someList = new LinkedList();
I could just add items to the end by doing:
list.addLast(x);
But how can I do it here?
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d ;
next = n ;
}
public static Node addLast(Node header, Object x) {
// save the reference to the header so we can return it.
Node ret = header;
// check base case, header is null.
if (header == null) {
return new Node(x, null);
}
// loop until we find the end of the list
while ((header.next != null)) {
header = header.next;
}
// set the new node to the Object x, next will be null.
header.next = new Node(x, null);
return ret;
}
}
You want to navigate through the entire linked list using a loop and checking the "next" value for each node. The last node will be the one whose next value is null. Simply make this node's next value a new node which you create with the input data.
node temp = first; // starts with the first node.
while (temp.next != null)
{
temp = temp.next;
}
temp.next = new Node(header, x);
That's the basic idea. This is of course, pseudo code, but it should be simple enough to implement.
public static Node insertNodeAtTail(Node head,Object data) {
Node node = new Node(data);
node.next = null;
if (head == null){
return node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
return head;
}
}
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) { //if the list is empty, set head and tail to this first node
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
Create a new node with the given value
If the list is empty, point head and tail to the new node
If the list is not empty, set the old tail.next to be the new node
In either case, update the tail pointer to be the new node
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().
Node.java
package in.datastructure.java.LinkedList;
/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
int data;
Node next;
Node (int data){
this.data = data;
}
public String toString(){
return this.data+"--"+ this.next;
}
}
LinkedList.java
package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;
public class LinkedList {
Node head;
Node lastx;
/**
* #description To append node at end looping all nodes from head
* #param data
*/
public void addLast(int data){
if(head == null){
head = new Node(data);
return;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
}
/**
* #description This keep track on last node and append to it
* #param data
*/
public void addLastx(int data){
if(head == null){
head = new Node(data);
lastx = head;
return;
}
if(lastx.next == null){
lastx.next = new Node(data);
lastx = lastx.next;
}
}
public String toString(){
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
Node current = head;
while(current.next != null) {
arrayList.add(current.data);
current = current.next;
}
if(current.next == null) {
arrayList.add(current.data);
}
return arrayList.toString();
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
/**
* #description Checking the code optimization of append code
*/
Date startTime = new Date();
for (int i = 0 ; i < 100000 ; i++){
ll.addLastx(i);
}
Date endTime = new Date();
System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
System.out.println(ll.toString());
}
}
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}

binary Tree: printing the data in ascending order

I am a beginner in java .. I have just started the data structure online.
I want to print the values i have added to the binary tree in ascending order.
I have created a method print and tried it with these values:
9,5,2,8,3
It printed this output and stopped
2 , 3 ,8
the Nodes have to constructors :
Constructor 1
public Node(int value){
this.Value=value;
isEmpty=false;
this.left=new Node();
this.right=new Node();
}
Constructor 2
public Node(){
isEmpty=true;
}
The Adding method :
public void add(int value) {
if (Objects.isNull(root)) {
root = new Node(value);
root.isEmpty = false;
}
Node current = root;
while (true) {
if (value < current.Value) {
if (current.left.isEmpty) {
current.left.prev = current;
current = current.left;
current.Value = value;
current.isEmpty = false;
current.left = new Node();
current.right = new Node();
break;
} else {
current = current.left;
}
} else {
if (current.right.isEmpty) {
current.right.prev = current;
current = current.right;
current.Value = value;
current.isEmpty = false;
current.left = new Node();
current.right = new Node();
break;
} else {
current = current.right;
}
}
}
}
The Print method
ArrayList<Node> list = new ArrayList();
Node current = root;while(true){
if(!current.left.isEmpty ){
if(!list.contains(current.left)){
current=current.left;
continue;
}
} else {
System.out.println(current.Value);
list.add(current);
if(!current.right.isEmpty && !list.contains(current.right)){
current=current.right;
continue;
}
current=current.prev.prev;
}
To print data from BST you need to do inorder traversal. In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used.
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
/* Given a binary tree, print its nodes in inorder*/
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
if(!node.isEmpty){
System.out.print(node.value+ " ");
}
/* now recur on right child */
printInorder(node.right);
}
Time Complexity: O(n)
If the tree is not BST. You can create List and write the tree's values into the list and sort the list in ascending order.
List<Integer> treeValues = new ArrayList<Integer>();
List<Integer> treeToList(Node node){
if (node == null)
return;
printInorder(node.left);
if(!node.isEmpty){
treeValues.add(node.value);
}
printInorder(node.right);
}
void sortedTree(Node node){
List<Integer> treeData = treeToList(node);
Collections.sort(treeData);
for(int i=0; i<treeData.size();i++ ){
System.out.println(treeData.get(i));
}
}

Binary Tree implementation for adding nodes level by level

I have been trying to write a program for creating a binary tree .I wish add nodes level by level .When i google the topic all i get is binary search tree .
here is the code
public class BinaryTree
{
public static void main(String[] args)
throws NullPointerException
{
Tree myTree = new Tree();
myTree.add(2,new Node(4));
myTree.add(4,new Node(5));
myTree.add(2,new Node(6));
//myTree.add(2,new Node(7));
}
}
class Node
{
int data;
boolean visited;
Node left,right;
Node(int data)
{
left=null;
right=null;
visited=false;
this.data=data;
}
}
class Tree
{
Node root;
int level,cLevel;
Tree()
{
root=null;
level=0;
cLevel=level-1;
}
protected void add(int data,Node node)
{
System.out.println("node.data k: "+node.data);
Node t;
if(root==null)
{
Node n=new Node(data);
root=n;
root.visited=true;
System.out.println("root visited"+root.data+""+root.visited);
level++;
cLevel++;
return;
}
while(root!=null)
{
}
}
}
I want to add new nodes level by level ,new level should not be created until a level isnt comleted ,all i get by googling is binary search tree .what should i do ,i have tried to use
depth first and breath first approach which didnt prrove helpfull .
You could achieve this by maintaining a queue of nodes which do not yet have two children. Every time you add a new node, stick it on the end of this queue, and also make it a child of the node at the front of this queue. Once the node at the front has two children, remove it from the queue. This way you'll build it up one level at a time, left to right, and only move on to the next level once the current one is finished.
You could also try "Limited Depth-first search"
A recursive implementation in Java using part of your code could be:
class Tree
{
Node root;
int level,cLevel;
Tree()
{
root=null;
level=0;
cLevel=level-1;
}
protected void add(int data)
{
System.out.println("data k: "+ data);
Node t;
if(root==null)
{
root=new Node(data);
level++;
} else {
cLevel = 0;
boolean added = add(data, root);
//Couldn't add to current level, add new level
if (!added){
level++;
cLevel = 0;
add(data, root);
}
}
}
private boolean add(int data, Node node)
{
cLevel++;
boolean added;
//Depth limited
if (cLevel<=level){
added = true;
//Try to add to current node
if (node.left == null)
node.left = new Node(data);
else if (node.right == null)
node.right = new Node(data);
else if (!add(data, node.left)) //Recursively trying to add to children
added = add(data, node.right);
} else {
added=false;
}
cLevel--;
return added;
}
}
Hope it helps.
Done with it.Thanks Animatinator .Although i have tested it with hardcode as i do not have time right now ,i have a paper early morning of Compiler Construction .
protected void add(int data,Tree mytree)
{
if(root==null)
{
root=new Node(data);
myList.addLast(root);
root.count++;
return;
}
Node node=mytree.myList.getFirst();
if(root!=null)
{
if(node.left==null)
{
node.count++;
node.left=new Node(data);
mytree.myList.add(node.left);
return;
}
else
{
node.count++;
node.right=new Node(data);
mytree.myList.add(node.right);
}
if(node.left!=null & node.right!=null)
{
mytree.myList.removeFirst();
}
}
}

Adding items to end of linked list

I'm studying for an exam, and this is a problem from an old test:
We have a singly linked list with a list head with the following declaration:
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d;
next = n;
}
}
Write a method void addLast(Node header, Object x) that adds x at the end of the list.
I know that if I actually had something like:
LinkedList someList = new LinkedList();
I could just add items to the end by doing:
list.addLast(x);
But how can I do it here?
class Node {
Object data;
Node next;
Node(Object d,Node n) {
data = d ;
next = n ;
}
public static Node addLast(Node header, Object x) {
// save the reference to the header so we can return it.
Node ret = header;
// check base case, header is null.
if (header == null) {
return new Node(x, null);
}
// loop until we find the end of the list
while ((header.next != null)) {
header = header.next;
}
// set the new node to the Object x, next will be null.
header.next = new Node(x, null);
return ret;
}
}
You want to navigate through the entire linked list using a loop and checking the "next" value for each node. The last node will be the one whose next value is null. Simply make this node's next value a new node which you create with the input data.
node temp = first; // starts with the first node.
while (temp.next != null)
{
temp = temp.next;
}
temp.next = new Node(header, x);
That's the basic idea. This is of course, pseudo code, but it should be simple enough to implement.
public static Node insertNodeAtTail(Node head,Object data) {
Node node = new Node(data);
node.next = null;
if (head == null){
return node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
return head;
}
}
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) { //if the list is empty, set head and tail to this first node
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
Create a new node with the given value
If the list is empty, point head and tail to the new node
If the list is not empty, set the old tail.next to be the new node
In either case, update the tail pointer to be the new node
Here is a partial solution to your linked list class, I have left the rest of the implementation to you, and also left the good suggestion to add a tail node as part of the linked list to you as well.
The node file :
public class Node
{
private Object data;
private Node next;
public Node(Object d)
{
data = d ;
next = null;
}
public Object GetItem()
{
return data;
}
public Node GetNext()
{
return next;
}
public void SetNext(Node toAppend)
{
next = toAppend;
}
}
And here is a Linked List file :
public class LL
{
private Node head;
public LL()
{
head = null;
}
public void AddToEnd(String x)
{
Node current = head;
// as you mentioned, this is the base case
if(current == null) {
head = new Node(x);
head.SetNext(null);
}
// you should understand this part thoroughly :
// this is the code that traverses the list.
// the germane thing to see is that when the
// link to the next node is null, we are at the
// end of the list.
else {
while(current.GetNext() != null)
current = current.GetNext();
// add new node at the end
Node toAppend = new Node(x);
current.SetNext(toAppend);
}
}
}
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
Here's a hint, you have a graph of nodes in the linked list, and you always keep a reference to head which is the first node in the linkedList.
next points to the next node in the linkedlist, so when next is null you are at the end of the list.
The addLast() needs some optimisation as the while loop inside addLast() has O(n) complexity. Below is my implementation of LinkedList. Run the code with ll.addLastx(i) once and run it with ll.addLast(i) again , you can see their is a lot of difference in processing time of addLastx() with addLast().
Node.java
package in.datastructure.java.LinkedList;
/**
* Created by abhishek.panda on 07/07/17.
*/
public final class Node {
int data;
Node next;
Node (int data){
this.data = data;
}
public String toString(){
return this.data+"--"+ this.next;
}
}
LinkedList.java
package in.datastructure.java.LinkedList;
import java.util.ArrayList;
import java.util.Date;
public class LinkedList {
Node head;
Node lastx;
/**
* #description To append node at end looping all nodes from head
* #param data
*/
public void addLast(int data){
if(head == null){
head = new Node(data);
return;
}
Node last = head;
while(last.next != null) {
last = last.next;
}
last.next = new Node(data);
}
/**
* #description This keep track on last node and append to it
* #param data
*/
public void addLastx(int data){
if(head == null){
head = new Node(data);
lastx = head;
return;
}
if(lastx.next == null){
lastx.next = new Node(data);
lastx = lastx.next;
}
}
public String toString(){
ArrayList<Integer> arrayList = new ArrayList<Integer>(10);
Node current = head;
while(current.next != null) {
arrayList.add(current.data);
current = current.next;
}
if(current.next == null) {
arrayList.add(current.data);
}
return arrayList.toString();
}
public static void main(String[] args) {
LinkedList ll = new LinkedList();
/**
* #description Checking the code optimization of append code
*/
Date startTime = new Date();
for (int i = 0 ; i < 100000 ; i++){
ll.addLastx(i);
}
Date endTime = new Date();
System.out.println("To total processing time : " + (endTime.getTime()-startTime.getTime()));
System.out.println(ll.toString());
}
}
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}

Categories