We've already seen many implementations of tree and its uses in java. Lets look at a simple implementation of traversing on a tree in C++. Code has been given below which I think is quite self descriptive.
Regards,
Jack
Regards,
Jack
package dsa.tries;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class TrieLoader {
public static Trie trieDSA;
public static void main(String[] args) {
TrieLoader trieLoader = new TrieLoader();
trieLoader.load();
new TrieTestFrame();
}
public void load(){
trieDSA = new Trie();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("src/properties/words.txt")));
String eachLine = null;
while((eachLine=br.readLine())!=null){
trieDSA.insert(eachLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package dsa.tries;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TrieTestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel basePanel = new JPanel();
private JTextField textField = new JTextField(20);
private JButton button = new JButton("Check");
public TrieTestFrame(){
designUI();
}
private void designUI(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("TRIE Test");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(TrieLoader.trieDSA.search(textField.getText())){
JOptionPane.showMessageDialog(basePanel, "The word you entered exist!!");
}else{
JOptionPane.showMessageDialog(basePanel, "The word you entered does not exist!!","Error",JOptionPane.ERROR_MESSAGE);
}
}
});
basePanel.add(textField);
basePanel.add(button);
add(basePanel);
this.setSize(400,100);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setLocation(screenWidth / 2 - 200, screenHeight / 2 - 50);
this.setVisible(true);
}
}
public boolean search(String s){
Node current = root;
while(current != null){
for(int i=0;i<s.length();i++){
if(current.subNode(s.charAt(i)) == null)
return false;
else
current = current.subNode(s.charAt(i));
}
/*
* This means that a string exists, but make sure its
* a word by checking its 'marker' flag
*/
if (current.marker == true)
return true;
else
return false;
}
return false;
}
public void insert(String s){
Node current = root;
if(s.length()==0) //For an empty character
current.marker=true;
for(int i=0;i<s.length();i++){
Node child = current.subNode(s.charAt(i));
if(child!=null){
current = child;
}
else{
current.child.add(new Node(s.charAt(i)));
current = current.subNode(s.charAt(i));
}
// Set marker to indicate end of the word
if(i==s.length()-1)
current.marker = true;
}
} package dsa.tries;
import java.util.Collection;
import java.util.LinkedList;
/**
* @author Braga
*/
public class Node {
char content;
boolean marker;
Collection<Node> child;
public Node(char c){
child = new LinkedList<Node>();
marker = false;
content = c;
}
public Node subNode(char c){
if(child!=null){
for(Node eachChild:child){
if(eachChild.content == c){
return eachChild;
}
}
}
return null;
}
}
package dsa.tries;
public class Trie{
private Node root;
public Trie(){
root = new Node(' ');
}
public void insert(String s){
Node current = root;
if(s.length()==0) //For an empty character
current.marker=true;
for(int i=0;i<s.length();i++){
Node child = current.subNode(s.charAt(i));
if(child!=null){
current = child;
}
else{
current.child.add(new Node(s.charAt(i)));
current = current.subNode(s.charAt(i));
}
// Set marker to indicate end of the word
if(i==s.length()-1)
current.marker = true;
}
}
public boolean search(String s){
Node current = root;
while(current != null){
for(int i=0;i<s.length();i++){
if(current.subNode(s.charAt(i)) == null)
return false;
else
current = current.subNode(s.charAt(i));
}
/*
* This means that a string exists, but make sure its
* a word by checking its 'marker' flag
*/
if (current.marker == true)
return true;
else
return false;
}
return false;
}
}
public void insert(String s); public boolean search(String s);
char content; boolean marker; Collection<Node> child;
package dsa.stack;
import dsa.linkedlist.SinglyLinkedList;
public class Stack<E> extends SinglyLinkedList<E>{
public static final int MAX_STACK_SIZE = 100;
public E pop() throws StackEmptyException{
if(this.size()==0){
throw new StackEmptyException();
}
return this.removeAtFirst();
}
public E peek() throws StackEmptyException{
if(this.size()==0){
throw new StackEmptyException();
}
return this.getFirst().data;
}
public void push(E data) throws StackOverflowException{
if(this.size()>MAX_STACK_SIZE){
throw new StackOverflowException();
}
this.insertAtFirst(data);
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
try{
System.out.println("Pushing 1, 2, 3, 4, 5");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Pop once : "+stack.pop());
System.out.println("Peek once : "+stack.peek());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
}catch(StackEmptyException e){
System.out.println(e.getMessage());
}catch(StackOverflowException e){
System.out.println(e.getMessage());
}
}
}
/*
SAMPLE OUTPUT:
Pushing 1, 2, 3, 4, 5
Pop once : 5
Peek once : 4
Pop once : 4
Pop once : 3
Pop once : 2
Pop once : 1
Stack is empty!
*/
package dsa.stack;
public class StackEmptyException extends Exception{
public StackEmptyException(){
super("Stack is empty!");
}
}
package dsa.stack;
public class StackOverflowException extends Exception{
public StackOverflowException(){
super("Stack Overflown");
}
}
package dsa.linkedlist;
public class FindKthElementFromLast {
public static void main(String args[]){
FindKthElementFromLast kthFromLastFinder = new FindKthElementFromLast();
SinglyLinkedList<Integer> originalList = kthFromLastFinder.getLabRatList(8);
System.out.println("Original List : "+originalList.toString());
kthFromLastFinder.findFromLast(originalList, 3);
}
private void findFromLast(SinglyLinkedList<Integer> singlyLinkedList, int k) {
Node far, near;
//initialize far and near pointers
far = near = singlyLinkedList.start;
//Move the far pointer k times from the starting position
System.out.print("kth node from last for k = "+k+" is ");
while((k--)!=0){
far = far.next;
}
while(far!=null){
near = near.next;
far = far.next;
}
System.out.println(near.data);
}
private SinglyLinkedList<Integer> getLabRatList(int count){
SinglyLinkedList<Integer> sampleList = new SinglyLinkedList<Integer>();
for(int i=1;i<=count;i++){
sampleList.add(i);
}
return sampleList;
}
}
//SAMPLE OUTPUT
//Original List : 1, 2, 3, 4, 5, 6, 7, 8
//kth node from last for k = 3 is 6
Cheers,class Node {
Node left;
Node right;
int data;
}
If you look at the above structure, there are no parent nodes and the given tree is not a Binary Search Tree which makes the problem all the more complicated.package dsa.tree;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
/**
* Program to find the Least Common Ancestor without
* for a Binary Tree (Not a BST). The Node does not have
* a parent pointer. The direction of the tree is one sided
* @author Braga
*
*/
public class LCSBinaryTree {
private Node n1,n2;
public static void main(String args[]){
LCSBinaryTree nodeFinder = new LCSBinaryTree();
nodeFinder.find();
}
public void find(){
Tree t = getSampleTree();
Node commonParent = findCommonParent(t,n1,n2);
if(commonParent == null){
System.out.println("Common Parent for "+n1.data+" and "+n2.data+" is null");
}else{
System.out.println("Common Parent for "+n1.data+" and "+n2.data+" is "+commonParent.data);
}
}
private Tree getSampleTree() {
Tree bsTree = new BinarySearchTree();
int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
for(int i=0;i<randomData.length;i++){
bsTree.add(randomData[i]);
}
n1 = bsTree.search(76);
n2 = bsTree.search(334);
return bsTree;
}
public Node findCommonParent(Tree t, Node node1, Node node2){
TracePath pathTracer = new TracePath();
/**
* If either of the nodes is root, then there is no common
* parent
*/
if(node1.equals(t.getRoot()) || node2.equals(t.getRoot())){
return null;
}
//Using the path tracer, find the path of two nodes in 2*O(n) time.
Stack<Node> path1 = pathTracer.trace(t, node1);
Stack<Node> path2 = pathTracer.trace(t, node2);
//All that is left to do is to find the common parent now.
Set<Node> firstPath = new HashSet<Node>();
for(Node iNode:path1){
firstPath.add(iNode);
}
while(!path2.isEmpty()){
Node currentNode = path2.pop();
if(firstPath.contains(currentNode)){
if(!path2.isEmpty() && firstPath.contains(currentNode = path2.peek())){
return path2.peek();
}
return currentNode;
}
}
return null;
}
}
//SAMPLE OUTPUTS
//Common Parent for 887 and 334 is 43
//Common Parent for 43 and 334 is null
//Common Parent for 6 and 334 is 43
//Common Parent for 76 and 334 is 46
Cheers,package dsa.tree;
import java.util.Stack;
public class TracePath {
private Node n1;
private Stack<Node> mainStack = null;
public static void main(String args[]){
TracePath nodeFinder = new TracePath();
nodeFinder.find();
}
public void find(){
Tree t = getSampleTree();
trace(t,n1);
for(Node iNode:mainStack){
System.out.println(iNode.data);
}
}
private Tree getSampleTree() {
Tree bsTree = new BinarySearchTree();
int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
for(int i=0;i<randomData.length;i++){
bsTree.add(randomData[i]);
}
n1 = bsTree.search(76);
return bsTree;
}
public Stack<Node> trace(Tree t, Node node){
mainStack = new Stack<Node>();
trace(t.getRoot(),node);
return mainStack;
}
private boolean trace(Node parent, Node node){
mainStack.push(parent);
if(node.equals(parent)){
return true;
}
if(parent.left != null){
if (trace(parent.left, node))
return true;
}
if(parent.right!=null){
if (trace(parent.right, node))
return true;
}
mainStack.pop();
return false;
}
}

package dsa.tree;
import java.util.HashSet;
import java.util.Set;
public class FindCommonNode {
private Node n1,n2;
public static void main(String args[]){
FindCommonNode nodeFinder = new FindCommonNode();
nodeFinder.find();
}
public void find(){
Tree t = getSampleTree();
Node commonParent = findCommonParent(t,n1,n2);
System.out.println("Common Parent : "+commonParent.data);
}
private Tree getSampleTree() {
Tree bsTree = new BinarySearchTree();
int randomData[] = {43,887,11,3,8,33,6,0,46,32,78,76,334,45};
for(int i=0;i<randomData.length;i++){
bsTree.add(randomData[i]);
}
n1 = bsTree.search(45);
n2 = bsTree.search(334);
return bsTree;
}
public Node findCommonParent(Tree t, Node node1, Node node2){
Set<Node> firstNodeAddrSet = new HashSet<Node>();
//Traverse till root
while(node1!=null){
firstNodeAddrSet.add(node1);
node1 = node1.parent;
}
while(!firstNodeAddrSet.contains(node2) && node2!=null){
node2 = node2.parent;
}
return node2;
}
}
package dsa.linkedlist;
public class FindCenterOfAList {
public static void main(String args[]){
FindCenterOfAList ratList = new FindCenterOfAList();
ratList.test(10);//TEST FOR EVEN
ratList.test(17);//TEST FOR ODD
ratList.test(1);//TEST FOR SINGLE
ratList.test(0);//TEST FOR ZERO OR LESS
}
public int[] getMidItem(SinglyLinkedList<Integer> listToCheck){
Node<Integer> singleJump = listToCheck.start;
Node<Integer> doubleJump = listToCheck.start;
while(doubleJump.next!=null && doubleJump.next.next!=null){
singleJump = singleJump.next;
doubleJump = doubleJump.next.next;
}
int[] midItem = null;
if(doubleJump.next == null){
midItem = new int[1];
midItem[0] = singleJump.data;
}else if(doubleJump.next.next == null){
midItem = new int[2];
midItem[0] = singleJump.data;
midItem[1] = singleJump.next.data;
}
return midItem;
}
private void test(int sampleSize){
if(sampleSize<1){
System.out.println("List is empty!");
return;
}
SinglyLinkedList<Integer> randomList = giveMeAList(sampleSize);
System.out.print("For list : ");stringify(randomList);
int[] midItem = getMidItem(randomList);
if(midItem.length == 1){
System.out.println("Middle Item : "+midItem[0]);
}else if(midItem.length == 2){
System.out.println("Middle Items : "+midItem[0]+", "+midItem[1]);
}
System.out.println();
}
private SinglyLinkedList<Integer> giveMeAList(int length){
SinglyLinkedList<Integer> sampleList = new SinglyLinkedList<Integer>();
for(int i=1;i<=length;i++){
sampleList.add(i);
}
return sampleList;
}
private void stringify(SinglyLinkedList<Integer> ratList) {
for(int i=0;i<ratList.size;i++){
System.out.print(ratList.getNodeAt(i).data+" ");
}
System.out.println();
}
}
/*
-------OUTPUT--------
For list : 1 2 3 4 5 6 7 8 9 10
Middle Items : 5, 6
For list : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Middle Item : 9
For list : 1
Middle Item : 1
List is empty!
*/
Order | Sequence |
In-order | 9, 12, 14, 17, 19, 23, 50, 54, 67, 72, 76 |
Pre-order | 50, 17, 9, 14, 12, 23, 19, 76, 54, 72, 67 |
Post-order | 12, 14, 9, 19, 23, 17, 67, 72, 54, 76, 50 |