Differences between following two functions - binary-tree

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 ?
}
}

Related

why can't i make these functions static?

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

heap data structure via pointers

Suggest an efficient way to find last position in heap satisfying the following conditions:
1) via pointers not via array
2) where we can insert or delete node
I could find it in O(n) time complexity but suggest a way which is of O(logn) or O(1) time complexity.
I'm assuming here that you mean a binary heap.
If you know how many nodes are in the heap, you can find the last node in O(log n) time by converting the count to binary, and then following the path of bits from high to low. That is, take the left node if the bit is 0, and the right node if the bit is 1.
For example, if there are three nodes in the heap, the binary representation of the count is 11. The root is always the first node, leaving you with 1. Then you take the right branch to get the last node.
Say there are 5 nodes in the heap:
1
2 3
4 5
In binary, that's 101. So you take the root. The next digit is 0 so you take the left branch. The next digit is 1, so you take the right branch, leaving you at node 5.
If you want the next available slot, you add 1 to the count and do the same thing. So 6 would be 110. You take the root, then the right branch, and the left child of 3 is where you'd add the new node.
You can do the same kind of thing with any d-ary heap, except that instead of converting to binary you convert to base d. So if your heap nodes each have up to three children, you'd convert the count to base 3, and use essentially the same logic as above.
An alternative is to maintain a reference to the last node in the heap, updating it every time you modify the heap. Or, if you want to know where the next node would be placed, you maintain a reference to the first node that doesn't have two children. That's O(1), but requires bookkeeping on every insertion or deletion.
I am answering my own question, There is no need to keep track of next pointer while inserting in heap (heap via pointers), even there is no need to keep track of parent, i am attaching running java code for heap, all possible method are included in it, getMin() = O(1), insert() = O(logn), extractMin = O(logn), decreasePriorityOfHead = O(logn), I have implemented it for generic code so it would be helpful to understand generic concept also.
class MinHeap<E extends Comparable<E>> {
private DoublyNode<E> root;
private int size = 0;
public DoublyNode<E> getRoot() {
return root;
}
public void setRoot(DoublyNode<E> root) {
this.root = root;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public MinHeap() {
}
public MinHeap(E data) {
this.root = new DoublyNode<E>(data);
this.size++;
}
private class NodeLevel<E extends Comparable<E>> {
private int level;
private DoublyNode<E> node;
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public DoublyNode<E> getNode() {
return node;
}
public void setNode(DoublyNode<E> node) {
this.node = node;
}
public NodeLevel(DoublyNode<E> node, int level) {
this.node = node;
this.level = level;
}
}
public void insert(E data) {
if (this.size == 0) {
this.root = new DoublyNode<E>(data);
this.size++;
return;
}
DoublyNode<E> tempRoot = this.root;
Integer insertingElementPosition = this.size + 1;
char[] insertingElementArray = Integer.toBinaryString(
insertingElementPosition).toCharArray();
DoublyNode<E> newNode = new DoublyNode<E>(data);
int i;
for (i = 1; i < insertingElementArray.length - 1; i++) {
if (newNode.getData().compareTo(tempRoot.getData()) < 0) {
this.swap(newNode, tempRoot);
}
char c = insertingElementArray[i];
if (c == '0') {
tempRoot = tempRoot.getLeft();
} else {
tempRoot = tempRoot.getRight();
}
}
// newNode.setParent(tempRoot);
if (newNode.getData().compareTo(tempRoot.getData()) < 0) {
this.swap(newNode, tempRoot);
}
if (insertingElementArray[i] == '0') {
tempRoot.setLeft(newNode);
} else {
tempRoot.setRight(newNode);
}
this.size++;
}
public void swap(DoublyNode<E> node1, DoublyNode<E> node2) {
E temp = node1.getData();
node1.setData(node2.getData());
node2.setData(temp);
}
public E getMin() {
if (this.size == 0) {
return null;
}
return this.root.getData();
}
public void heapifyDownWord(DoublyNode<E> temp) {
if (temp == null) {
return;
}
DoublyNode<E> smallerChild = this.getSmallerChild(temp);
if (smallerChild == null) {
return;
}
if (smallerChild.getData().compareTo(temp.getData()) < 0) {
this.swap(temp, smallerChild);
this.heapifyDownWord(smallerChild);
}
}
public DoublyNode<E> getSmallerChild(DoublyNode<E> temp) {
if (temp.getLeft() != null && temp.getRight() != null) {
return (temp.getLeft().getData()
.compareTo(temp.getRight().getData()) < 0) ? temp.getLeft()
: temp.getRight();
} else if (temp.getLeft() != null) {
return temp.getLeft();
} else {
return temp.getRight();
}
}
public E extractMin() {
if (this.root == null) {
return null;
}
E temp = this.root.getData();
if (this.root.getLeft() == null && this.root.getRight() == null) {
this.root = null;
this.size--;
return temp;
}
DoublyNode<E> parentOfLastData = this.getParentOfLastData();
if (parentOfLastData.getRight() != null) {
this.root.setData(parentOfLastData.getRight().getData());
parentOfLastData.setRight(null);
} else {
this.root.setData(parentOfLastData.getLeft().getData());
parentOfLastData.setLeft(null);
}
this.heapifyDownWord(this.root);
return temp;
}
public DoublyNode<E> getParentOfLastData() {
if (this.size == 0) {
return null;
}
DoublyNode<E> tempRoot = this.root;
Integer insertingElementPosition = this.size;
char[] insertingElementArray = Integer.toBinaryString(
insertingElementPosition).toCharArray();
int i;
for (i = 1; i < insertingElementArray.length - 1; i++) {
char c = insertingElementArray[i];
if (c == '0') {
tempRoot = tempRoot.getLeft();
} else {
tempRoot = tempRoot.getRight();
}
}
return tempRoot;
}
public DoublyNode<E> getParentOfLastEmptyPosition() {
if (this.size == 0) {
return null;
}
DoublyNode<E> tempRoot = this.root;
Integer insertingElementPosition = this.size + 1;
char[] insertingElementArray = Integer.toBinaryString(
insertingElementPosition).toCharArray();
System.out.println(insertingElementArray.toString());
int i;
for (i = 1; i < insertingElementArray.length - 1; i++) {
char c = insertingElementArray[i];
if (c == '0') {
tempRoot = tempRoot.getLeft();
} else {
tempRoot = tempRoot.getRight();
}
}
return tempRoot;
}
public void print() {
if (this.root == null) {
System.out.println("Heap via pointer is empty!");
return;
}
System.out.println("\n Heap via pointer is:- ");
Queue<NodeLevel<E>> dataQueue = new Queue<NodeLevel<E>>();
Queue<Space> spaceQueue = new Queue<Space>();
dataQueue.enQueue(new NodeLevel<E>(this.root, 1));
int heightOfTree = this.getHeightOfHeap();
Double powerHeghtBST = Math.pow(heightOfTree, 2);
spaceQueue.enQueue(new Space(powerHeghtBST.intValue(), false));
while (!dataQueue.isEmpty()) {
Space space = spaceQueue.deQueue();
NodeLevel<E> nodeLevel = dataQueue.deQueue();
while (space.isNullSpace()) {
space.printNullSpace();
spaceQueue.enQueue(space);
space = spaceQueue.deQueue();
}
space.printFrontSpace();
System.out.print(nodeLevel.getNode().getData().printingData());
space.printBackSpace();
if (nodeLevel.getNode().getLeft() != null) {
dataQueue.enQueue(new NodeLevel<E>(nodeLevel.getNode()
.getLeft(), nodeLevel.getLevel() + 1));
spaceQueue.enQueue(new Space(space.getSpaceSize() / 2, false));
} else {
spaceQueue.enQueue(new Space(space.getSpaceSize() / 2, true));
}
if (nodeLevel.getNode().getRight() != null) {
dataQueue.enQueue(new NodeLevel<E>(nodeLevel.getNode()
.getRight(), nodeLevel.getLevel() + 1));
spaceQueue.enQueue(new Space(space.getSpaceSize() / 2, false));
} else {
spaceQueue.enQueue(new Space(space.getSpaceSize() / 2, true));
}
if (!dataQueue.isEmpty()
&& nodeLevel.getLevel() + 1 == dataQueue.getFrontData()
.getLevel()) {
System.out.println("\n");
}
}
}
public int getHeightOfHeap() {
if (this.size == 0) {
return 0;
}
Double height = Math.log(this.size) / Math.log(2) + 1;
return height.intValue();
}
public void changePriorityOfHeapTop(E data) {
if (this.root == null) {
return;
}
this.root.setData(data);
this.heapifyDownWord(this.root);
}
}
interface Comparable<T> extends java.lang.Comparable<T> {
/**
* this methos returns a string of that data which to be shown during
* printing tree
*
* #return
*/
public String printingData();
}
public class PracticeMainClass {
public static void main(String[] args) {
MinHeap<Student> minHeap1 = new MinHeap<Student>();
minHeap1.insert(new Student(50, "a"));
minHeap1.insert(new Student(20, "a"));
minHeap1.insert(new Student(60, "a"));
minHeap1.insert(new Student(30, "a"));
minHeap1.insert(new Student(40, "a"));
minHeap1.insert(new Student(70, "a"));
minHeap1.insert(new Student(10, "a"));
minHeap1.insert(new Student(55, "a"));
minHeap1.insert(new Student(35, "a"));
minHeap1.insert(new Student(45, "a"));
minHeap1.print();
minHeap1.getMin();
minHeap1.print();
System.out
.println("\nminimum is:- " + minHeap1.getMin().printingData());
minHeap1.print();
System.out.println("\nminimum is:- "
+ minHeap1.extractMin().printingData());
minHeap1.print();
minHeap1.changePriorityOfHeapTop(new Student(75, "a"));
minHeap1.print();
}
}
class DoublyNode<E extends Comparable<E>> {
private E data;
private DoublyNode<E> left;
private DoublyNode<E> right;
// private DoublyNode<E> parent;
public DoublyNode() {
}
public DoublyNode(E data) {
this.data = data;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public DoublyNode<E> getLeft() {
return left;
}
public void setLeft(DoublyNode<E> left) {
this.left = left;
}
public DoublyNode<E> getRight() {
return right;
}
public void setRight(DoublyNode<E> right) {
this.right = right;
}
// public DoublyNode<E> getParent() {
// return parent;
// }
// public void setParent(DoublyNode<E> parent) {
// this.parent = parent;
// }
}
class Space {
private boolean isNullSpace = false;
private String frontSpace;
private String backSpace;
private String nullSpace;
private int spaceSize;
public boolean isNullSpace() {
return isNullSpace;
}
public void setNullSpace(boolean isNullSpace) {
this.isNullSpace = isNullSpace;
}
public int getSpaceSize() {
return spaceSize;
}
public void setSpaceSize(int spaceSize) {
this.spaceSize = spaceSize;
}
public Space(int spaceSize, boolean isNullSpace) {
this.isNullSpace = isNullSpace;
this.spaceSize = spaceSize;
if (spaceSize == 0) {
this.frontSpace = "";
this.backSpace = "";
this.nullSpace = " ";
} else if (spaceSize == 1) {
this.frontSpace = " ";
this.backSpace = "";
this.nullSpace = " ";
} else if (spaceSize == 2) {
this.frontSpace = " ";
this.backSpace = "";
this.nullSpace = " ";
} else {
this.frontSpace = String.format("%" + (spaceSize) + "s", " ");
this.backSpace = String.format("%" + (spaceSize - 2) + "s", " ");
this.nullSpace = String.format("%" + 2 * (spaceSize) + "s", " ");
}
}
public void printFrontSpace() {
System.out.print(this.frontSpace);
}
public void printBackSpace() {
System.out.print(this.backSpace);
}
public void printNullSpace() {
System.out.print(this.nullSpace);
}
}
class Queue<E> {
private Node<E> front;
private Node<E> rear;
private int queueSize = 0;
public Queue() {
}
public Queue(E data) {
this.front = new Node(data);
this.rear = this.front;
}
public void enQueue(E data) {
if (this.rear == null) {
this.rear = new Node(data);
this.front = this.rear;
} else {
Node newNode = new Node(data);
this.rear.setNext(newNode);
this.rear = newNode;
}
this.queueSize++;
}
public E deQueue() {
E returnValue;
if (this.front == null) {
return null;
} else if (this.front == this.rear) {
returnValue = this.front.getData();
this.front = null;
this.rear = null;
} else {
returnValue = this.front.getData();
this.front = this.front.getNext();
}
this.queueSize--;
return returnValue;
}
public void print() {
Node temp = this.front;
System.out.print("\n Queue is:- ");
if (temp == null) {
System.out.println(" Empty! ");
}
while (temp != null) {
System.out.print(temp.getData() + ",");
temp = temp.getNext();
}
}
public int getQueueSize() {
return queueSize;
}
public E getFrontData() {
if (this.front == null) {
System.out.println("queue is empty!");
return null;
}
return this.front.getData();
}
public E getRearData() {
if (this.rear == null) {
System.out.println("queue is empty!");
return null;
}
return this.rear.getData();
}
public boolean isEmpty() {
return this.front == null;
}
}
class Node<E> {
private E data;
private Node next;
public Node(E data) {
this.data = data;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class Student implements Comparable<Student> {
private int id;
private String name;
#Override
public int compareTo(Student student) {
if (this.id == student.id) {
return 0;
} else if (this.id < student.id) {
return -1;
} else {
return 1;
}
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String printingData() {
// String printingData = "{ id: "+this.id+" name: "+this.name+" }";
String printingData = String.valueOf(this.id);
return printingData;
}
}
Output of this code is:-
Heap via pointer is:-
10
30 20
35 40 70 60
55 50 45
Heap via pointer is:-
10
30 20
35 40 70 60
55 50 45
minimum is:- 10
Heap via pointer is:-
10
30 20
35 40 70 60
55 50 45
minimum is:- 10
Heap via pointer is:-
20
30 45
35 40 70 60
55 50
Heap via pointer is:-
30
35 45
50 40 70 60
55 75

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
}

C++ Linked list insert back

I am trying to create a function that will insert a node to the back of the list using linked list. I am new to using linked list and I have tried many different ways of doing an insertion at the end of the list but nothing seems to be working. The main passes the values one at a time to be inserted 2 4 5 8 9, and the output is 2 0 0 0 0. I do not whats causing this problem.
.h
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext){}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
~Node(){}
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
~AnyList();
//destructor
int getNumOfItems();
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
int count; //keeps track of number of nodes in the list
};
.cpp
void AnyList::insertBack(int b)
{
Node *temp = new Node;
if (ptrToFirst == NULL)
{
temp->setData(b);
ptrToFirst = temp;
}
else
{
Node *first = ptrToFirst;
while (first->getPtrToNext() != NULL)
{
first = first->getPtrToNext();
}
first->setPtrToNext(temp);
}
}
First, you really should be using the std::list or std::forward_list class instead of implementing the node handling manually:
#include <list>
class AnyList
{
public:
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
std::list<int> nodes; //nodes in the list
};
void AnyList::print() const
{
for (std::list<int>::const_iterator iter = nodes.begin(); iter != nodes.end(); ++iter)
{
int value = *iter;
// print value as needed...
}
}
void AnyList::destroyList()
{
nodes.clear();
}
void AnyList::getNumOfItems() const
{
return nodes.size();
}
void AnyList::insertBack(int b)
{
nodes.push_back(b);
}
void AnyList::deleteFirstNode()
{
if (!nodes.empty())
nodes.pop_front();
}
That being said, your manual implementation fails because you are likely not managing the nodes correctly (but you did not show everything you are doing). It should look something like this:
class Node
{
public:
Node() : data(0), ptrToNext(NULL) {}
Node(int theData, Node *newPtrToNext) : data(theData), ptrToNext(newPtrToNext) {}
~Node() {}
Node* getPtrToNext() const { return ptrToNext; }
int getData() const { return data; }
void setData(int theData) { data = theData; }
void setPtrToNext(Node *newPtrToNext) { ptrToNext = newPtrToNext; }
private:
int data;
Node *ptrToNext; //pointer that points to next node
};
class AnyList
{
public:
AnyList();
//default constructor
~AnyList();
//destructor
void print() const;
//Prints all values in the list.
void destroyList();
//Destroys all nodes in the list.
int getNumOfItems() const;
void insertBack(int b);
void deleteFirstNode();
private:
Node *ptrToFirst; //pointer to point to the first node in the list
Node *ptrToLast; //pointer to point to the last node in the list
int count; //keeps track of number of nodes in the list
};
AnyList:AnyList()
: ptrToFirst(NULL), ptrToLast(NULL), count(0)
{
}
void AnyList::print() const
{
for (Node *temp = ptrToFirst; temp != NULL; temp = temp->getPtrToNext())
{
int value = temp->getData();
// print value as needed...
}
}
AnyList::~AnyList()
{
destroyList();
}
void AnyList::destroyList()
{
Node *temp = ptrToFirst;
ptrToFirst = ptrToLast = NULL;
count = 0;
while (temp != NULL)
{
Node *next = temp->getPtrToNext();
delete temp;
temp = next;
}
}
int AnyList::getNumOfItems() const
{
return count;
}
void AnyList::insertBack(int b)
{
Node *temp = new Node(b, NULL);
if (ptrToFirst == NULL)
ptrToFirst = temp;
if (ptrToLast != NULL)
ptrToLast->setPtrToNext(temp);
ptrToLast = temp;
++count;
}
void AnyList::deleteFirstNode()
{
if (ptrToFirst == NULL)
return;
Node *temp = ptrToFirst;
ptrToFirst = temp->getPtrToNext();
if (ptrToLast == temp)
ptrToLast = NULL;
delete temp;
--count;
}

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