Site icon

Print binary search tree for given range K1 & K2 in java (DFS & example)

Example – print binary search tree for given range K1 & K2 in java

Fig 1: Binary Search Tree for given range
Fig 2: Binary Tree in Range of 10 and 125

Algorithm – print binary search tree  in range K1=10 & K2=125 using java

In Fig 2, we have shown evaluation condition on few nodes.

Program – Print binary search tree (BST) in range of K1 & K2 using java

1.) PrintInRangeBST Class:

package org.learn.Question;

import org.learn.PrepareTree.Node;

public class PrintInRangeBST {
	public static void printRange(Node root, int k1, int k2) {
		if (root == null)
			return;
		if (root.data >= k1 && root.data <= k2)
			System.out.printf("%d ", root.data);
		if (root.data > k1)
			printRange(root.left, k1, k2);
		if (root.data < k2)
			printRange(root.right, k1, k2);
	}
}

2.) Node Class:

package org.learn.PrepareTree;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}
	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class:

package org.learn.Client;

import org.learn.PrepareTree.Node;
import org.learn.Question.PrintInRangeBST;

public class App 
{
    public static void main( String[] args )
    {  
       //root level 0
       Node A = Node.createNode(100);
       //Level 1
       Node B = Node.createNode(50);
       Node C = Node.createNode(150);
       //Level 2
       Node D = Node.createNode(25);
       Node E = Node.createNode(75);
       Node F = Node.createNode(125);
       Node G = Node.createNode(175);
       //Level 3
       Node H = Node.createNode(120);
       Node I = Node.createNode(140);
       Node J = Node.createNode(160);
       Node K = Node.createNode(190);
             
       //connect Level 0 and 1
       A.left = B;
       A.right = C;
       //connect level 1 and level 2
       B.left = D;
       B.right = E;
       C.left = F;
       C.right = G;
       //Connect level 2 and level 3
       F.left = H;
       F.right = I;
       G.left = J;
       G.right = K;
       
       int K1 = 10;
       int K2 = 125;
       System.out.printf("Printing binary tree in range %d and %d\n",K1, K2);
       PrintInRangeBST.printRange(A, K1, K2);     
    }
}

Output – print binary search tree (BST) in range of K1 & K2 using java

Printing binary tree in range 10 and 125
100 50 25 75 125 120

Download Code – print binary search tree in range K1 & K2 (DFS)

Exit mobile version