why can't i make these functions static? - data-structures

why can't i just make inOrder and insert static and pass the object's root in the main function??
instead of creating interim functions of same naem with void return types and then call them in the main function
public TreeNode insert(TreeNode root, int value){ - make this static
if (root == null){
root = new TreeNode(value);
return root;
}
if (value<root.data){
root.left = insert(root.left,value);
}else {
root.right = insert(root.right, value);
}
return root;
}
public void insert(int value){ i am asking if i can eleminate this function
root = insert(root,value);
}
public void inOrder(){ - and this function
inOrder(root);
}
public void inOrder(TreeNode temp){ - make this static
if (temp == null){
return;
}
inOrder(temp.left);
System.out.print(temp.data);
inOrder(temp.right);
}
and in the main function i'll directly call insert(object.root, ) and inOrder(object.root)
i did this and it did not show any output

you can, but then you should make the call object.root = insert(object.root, ...)
The function insert(int value) modifies the objects root

Related

Differences between following two functions

I am writing code to delete a node with val 1. I have implemented two functions for it. both apparently seems same to me, but gives a different result. please, can anybody point out why its happening like this?
code:-
The two functions are
node deleteNodeWithVal1Funct1(node root)
void deleteNodeWithVal1Funct2(node root)
public class Doubt1 {
class node
{
int data;
node left, right;
public node()
{
this.data = 0;
left=right=null;
}
public node(int data)
{
this.data = data;
left=right=null;
}
} ;
public static void printTreeInoreder(node root)
{
if(root==null)
return;
printTreeInoreder(root.left);
System.out.print(" "+root.data);
printTreeInoreder(root.right);
}
public static node deleteNodeWithVal1Funct1(node root)
{
if(root==null)
return null;
if(root.data==1)
return null;
root.left=deleteNodeWithVal1Funct1(root.left);
root.right=deleteNodeWithVal1Funct1(root.right);
return root;
}
public static void deleteNodeWithVal1Funct2(node root)
{
if(root==null)
return ;
if(root.data==1)
{
root=null;
return;
}
deleteNodeWithVal1Funct2(root.left);
deleteNodeWithVal1Funct2(root.right);
}
public static void main(String s[])
{
Doubt1 ob=new Doubt1();
node tree=ob.new node(0); // 0
tree.left=ob.new node(1); // -> / \
tree.right=ob.new node(2); // 1 2
printTreeInoreder(tree); // gives 1 0 2
deleteNodeWithVal1Funct2(tree);
printTreeInoreder(tree); // gives 1 0 2 why ?why not 02 ?
deleteNodeWithVal1Funct1(tree);
printTreeInoreder(tree); // gives 0 2 why? whynot 1 0 2 ?
}
}

reverse singly linked list java?

I have a problem ,I can't run this method , I want to reverse the nodes in a single Linkedlist.I say all Posts from Stackoverflow about reverse but they are different with my code.
There is my code
public node reverse(node head) {
node p,q;
if(head==null) {
return head;
}
p=head;
q=p.next;
if(q==null) {
return p;
}
q=reverse(q);
p.next.next=p;
p.next=null;
return q;
}public void printList(){
node currentNode = head;
while(currentNode != null){
System.out.print(currentNode.data);
currentNode=currentNode.next;
}
}
Main class
public class main {
public static void main(String[] args) {
linkedlist obj = new linkedlist();
obj.insertFirst(1);
obj.insertFirst(2);
obj.insertFirst(3);
obj.insertFirst(4);
obj.insertFirst(5);
obj.reverse(head);
obj.printList();
please give me a solution by there code.
Reversed the linked list:
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
Your code makes little sense and hard to make it right. I would recommend to go for an easier and concise approach first like this.
public node reverse(node head) {
if(head == null || head->next == mull) {
return head;
}
node current = head;
node newHead = null;
node previous = null;
while(current != null) {
node nxt = current.next;
current.next = previous;
newHead = current;
previous = current;
current = nxt;
}
return newHead;
}

Solution to Finding Start of Loop in a Circular Singly Linked List

The common solution that I find to this problem is to use 2 pointers that advanced through the linked list at different intervals (i.e. have p1 traverse one node at a time and p2 traverse two nodes at a time) until p1 and p2 are equals. Example: Finding loop in a singly linked-list
But why can't we just use a Set to see if there are duplicate nodes (Provided that our nodes don't have their default equals and hashCode overwritten).
Apply the next algorithm replacing the methods first and next by the proper one as in your language
slow=llist.first
fast=slow.next
while(true)
{
if (slow==null || fast == null)
return false// not circular
if (fast==slow)
return true//it is cirular
fast=fast.next;if (fast!=null)fast=fast.next;
slow=slow.next;
}
here is a detailed example in C#:
public class Node<T>
{
public Node<T> Next { get; set; }
public T Value { get; set; }
}
class LinkedList<T>
{
public Node<T> First { get; set; }
public Node<T> Last { get; set; }
public void Add(T value)
{
Add(new Node<T> { Value = value });
}
public void Add(Node<T> node)
{
if (First == null)
{
First = node;
Last = node;
}
else
{
Last.Next = node;
Last = node;
}
}
}
static int IndexOfCiruclarity<T>(LinkedList<T> llist)
{
var slow = llist.First;
var fast = slow.Next;
int index = -1;
while (true)
{
index++;
if (slow == null || fast == null)
return -1;
if (fast == slow)
return index;
fast = fast.Next;
if (fast != null) fast = fast.Next;
else
return -1;
slow = slow.Next;
}
}
void TestCircularity()
{
LinkedList<int> r = new LinkedList<int>();
for (int i = 0; i < 10; i++)
r.Add(i);
r.Add(r.First);
var ci = IndexOfCiruclarity(r);
//ci = 9
}

I don't know what's wrong with my code - Binary Tree

I'm now making a Binary Tree in C++, using friend class.
But, something is wrong, and I cannot know what should I change
template <class Type>
class BinaryTree{
public:
BinaryTree(){
root = new BTNode<Type>();
currentNode = NULL;
}
~BinaryTree(){
delete root, currentNode;
};
void insertItem(Type data){
if(currentNode==NULL){
Item = data;
currentNode = root;
}
if(data<currentNode){
if(currentNode->Left.is_empty()){
currentNode->Left = new BTNode(data);
currentNode = root;
return;
}
else{
currentNode = currentNode->Left;
return insertItem(data);
}
}
if(data>currentNode){
if(currentNode->Right.is_empty()){
currentNode->Right = new BTNode(data);
currentNode = root;
return;
}
else{
currentNode = currentNode->Right;
return insertItem(data);
}
}
currentNode = root;
return;
}
void deleteItem(Type data){}
void is_empty(){
if (this == NULL) return 1;
else return 0;
}
void printInOrder(){
if(!(currentNode->Left).is_empty()){
currentNode = currentNode->Left;
}
}
private:
BTNode<Type>* currentNode;
BTNode<Type>* root;
};
and here the BTNode class that store the item of BinaryTree, and point the next Node:
template <class Type>
class BTNode{
public:
friend class BinaryTree<Type>;
BTNode(){}
BTNode(Type data){
Item = data;
}
~BTNode(){}
private:
Type Item;
BTNode<Type> *Left, *Right;
};
The Binary Tree class's BTNode*root point the first Node, and currentNode will point the 'current node' while doing something like insertion or merging the nodes.
But when I compile, the Compiler Error C2143 occurs in the BinaryTree class,
here:
BTNode<Type>* root;
BTNode<Type>* currentNode;
The error says that there is no toke ; in front of <
but I cannot know what is wrong
It appears as though BTNode isn't correctly defined inside the BinaryTree class. The compiler is not understanding that BTNode is a type. Make sure you're including and linking the files correctly.

Traversing the Binary Search Tree

I was reading through Introduction to algorithms i came across this problem about In-order Traversal of binary search tree without using a stack or recursion. Hint says to assume that testing of pointers for equality is a legitimate operation.I'm stuck finding the solution to this problem. Please give me some direction. I'm not looking for the code. Just give me the right direction.
Exact duplicate here
No stack nor recursion means you have to use pointers. Not giving you code nor the exact answer, since you asked not to :)
Think about how to explore the tree without using recursion: what would you need to do? What pointer(s) do you need to keep? Can a tree node have a pointer to the parent?
Hope it helps.
We need a Threaded Binary Tree to do in-order Traversal without recursion / stack.
Wiki says 'A binary tree is threaded by making all right child pointers that would normally be null point to the inorder successor of the node, and all left child pointers that would normally be null point to the inorder predecessor of the node'
So you are given a normal Binary Tree , Convert it into a Threaded Binary Tree which can be done using Morris Traversal.
What you are going to do in Morris Traversal is to connect each node with its in-order successor. So while visiting a node ,Search for its in-order predecessor and let it be Pred.
then make Pred->right=Current node and we have to revert back the changes too. You can better refer this http://www.geeksforgeeks.org/archives/6358 for a great explanation.
Hello Parminder i have implemented your question in java.Please check it once
class InorderWithoutRecursion {
public static void morrisTraversal(TreeNode root) {
TreeNode current,pre;
if(root == null)
return;
current = root;
while(current != null){
if(current.left == null){
System.out.println(current.data);
current = current.right;
}
else {
/* Find the inorder predecessor of current */
pre = current.left;
while(pre.right != null && pre.right != current)
pre = pre.right;
/* Make current as right child of its inorder predecessor */
if(pre.right == null){
pre.right = current;
current = current.left;
}
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else {
pre.right = null;
System.out.println(current.data);
current = current.right;
}
}
}
}
public static void main(String[] args) {
int[] nodes_flattened = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
TreeNode root = TreeNode.createMinimalBST(nodes_flattened);
morrisTraversal(root);
}
}
For TreeNode class below code will help you..
public class TreeNode {
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode parent;
public TreeNode(int d) {
data = d;
}
public void setLeftChild(TreeNode left) {
this.left = left;
if (left != null) {
left.parent = this;
}
}
public void setRightChild(TreeNode right) {
this.right = right;
if (right != null) {
right.parent = this;
}
}
public void insertInOrder(int d) {
if (d <= data) {
if (left == null) {
setLeftChild(new TreeNode(d));
} else {
left.insertInOrder(d);
}
} else {
if (right == null) {
setRightChild(new TreeNode(d));
} else {
right.insertInOrder(d);
}
}
}
public boolean isBST() {
if (left != null) {
if (data < left.data || !left.isBST()) {
return false;
}
}
if (right != null) {
if (data >= right.data || !right.isBST()) {
return false;
}
}
return true;
}
public int height() {
int leftHeight = left != null ? left.height() : 0;
int rightHeight = right != null ? right.height() : 0;
return 1 + Math.max(leftHeight, rightHeight);
}
public TreeNode find(int d) {
if (d == data) {
return this;
} else if (d <= data) {
return left != null ? left.find(d) : null;
} else if (d > data) {
return right != null ? right.find(d) : null;
}
return null;
}
private static TreeNode createMinimalBST(int arr[], int start, int end){
if (end < start) {
return null;
}
int mid = (start + end) / 2;
TreeNode n = new TreeNode(arr[mid]);
n.setLeftChild(createMinimalBST(arr, start, mid - 1));
n.setRightChild(createMinimalBST(arr, mid + 1, end));
return n;
}
public static TreeNode createMinimalBST(int array[]) {
return createMinimalBST(array, 0, array.length - 1);
}
}

Resources