Skip to content

Instantly share code, notes, and snippets.

public class DeleteTree {
// to delete a binary tree, we need to set all the node objects to null then
// garbage collection will take care of rest of the things
//do the post order traversal and set the node to null
public static Node deleteTree(Node root) {
if (root != null) {
deleteTree(root.left);
deleteTree(root.right);
System.out.println("Deleting Node:" + root.data);
root=null;
public class TreeTraversals {
public void inorderRecursive(Node root) {
if (root != null) {
inorderRecursive(root.left);
System.out.print(root.data + " ");
inorderRecursive(root.right);
}
}
import java.util.Stack;
public class InorderIretation {
public void inorderRecursive(Node root) {
if (root != null) {
inorderRecursive(root.left);
System.out.print(root.data + " ");
inorderRecursive(root.right);
}
import java.util.Stack;
public class PreOrderTree {
public void preOrderRecursive(Node root) {
if (root != null) {
System.out.print(root.data + " ");
preOrderRecursive(root.left);
preOrderRecursive(root.right);
}
import java.util.Stack;
public class PostorderTree {
public void postOrderRecursive(Node root) {
if (root != null) {
postOrderRecursive(root.left);
postOrderRecursive(root.right);
System.out.print(root.data + " ");
public class TreeToSumTree {
static Node newRoot;
public int SumTree(Node root){
if(root!=null){
int left = SumTree(root.left);//take the left tree sum
int right = SumTree(root.right);//take the right tree sum
int retData = root.data+left+right; // return data left+right+root
public class LeftLeavesSum {
// Do the inorder traversal
// check if node if the left child and leaf node
// if yes then add it to the sum
public static int leftLeavesSum = 0;
public static void leftSum(Node root, Node parent) {
if (root != null) {
import java.util.Comparator;
import java.util.PriorityQueue;
public class MaxRevenueTickets {
PriorityQueue<Integer> pq;
// we will create a max heap
public MaxRevenueTickets(int length) {
pq = new PriorityQueue<>(length, new Comparator<Integer>() {
public class ReverseInGrps {
public Node reveseGrps(Node head, int k){
int x = k;
Node head_next=null;
Node h = head;
Node head_prev = null;
while(h!=null && x>0){
head_next = h.next;
public class ReverseAlternateKNodes {
public static void main(String[] args) throws java.lang.Exception {
LinkedListT a = new LinkedListT();
for (int i = 1; i <= 12; i++) {
a.addAtEnd(i);
}
System.out.print("Original Link List 1 : ");
a.display(a.head);
int k = 2;
System.out.println("\n Recursion with 2k nodes where k = " +k);