Programming‎ > ‎Java‎ > ‎

Code




LinkedList


class ListNode
{
int key;
ListNode next;
public ListNode(int item)
{
key = item;
next = null;
}
}

public class LinkedList 
{
ListNode ptr;
public LinkedList()
{
ptr = null;
}
public void print()
{
ListNode cur = ptr;
while(null != cur)
{
System.out.println(cur.key);
cur = cur.next;
}
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.ptr = new ListNode(1);
list.ptr.next = new ListNode(2);
list.print();
}
}



Binary Tree


/* BinaryTree.java */

import java.util.Queue;
import java.util.LinkedList;

class Node
{
int key;
Node left;
Node right;

public Node(int item)
{
key = item;
left = null;
right = null;
}

public void print()
{
if (null != left)
left.print();
System.out.println(key);

if (null != right)
right.print();
}
}

class BinaryTree
{
Node root;

public BinaryTree()
{
root = null;
}

public BinaryTree(int item)
{
root = new Node(item);
}
public static void traverseInOrder(Node ptr)
{
if(null != ptr)
{
traverseInOrder(ptr.left);
System.out.println(ptr.key);
traverseInOrder(ptr.right);
}
}
public static void traversePreOrder(Node ptr)
{
if(null != ptr)
{
System.out.println(ptr.key);
traversePreOrder(ptr.left);
traversePreOrder(ptr.right);
}
}
public static void traversePostOrder(Node ptr)
{
if(null != ptr)
{
traversePostOrder(ptr.left);
traversePostOrder(ptr.right);
System.out.println(ptr.key);
}
}
public static void traverseLevelOrder(Node root) {
    if (root == null) {
        return;
    }
 
    Queue<Node> nodes = new LinkedList<>();
    nodes.add(root);
 
    while (!nodes.isEmpty()) {
 
        Node node = nodes.remove();
 
        System.out.print(" " + node.key);
 
        if (node.left != null) {
            nodes.add(node.left);
        }
 
        if (node.right!= null) {
            nodes.add(node.right);
        }
    }
}

public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();

tree.root = new Node(1);

tree.root.left = new Node(2);
tree.root.right = new Node(3);

tree.root.left.left = new Node(4);

//tree.root.print(); // Output 4 2 1 3
traverseLevelOrder(tree.root);

}
}





















Comments