xxxxxxxxxx
A binary tree is said to be a binary search tree if for every node, the left is smaller than it and the right is bigger than it.
Example
10
9 20
6 11 13 26
For example, try looking for 13 and 26.
13 is larger than 10, so go to the right.
13 is smaller than 20, so go to the left.
26 is larger than 10, so go to the right.
26 is larger than 20, so go to the right.
xxxxxxxxxx
// C++ program to demonstrate insertion
// in a BST recursively.
#include <iostream>
using namespace std;
class BST {
int data;
BST *left, *right;
public:
// Default constructor.
BST();
// Parameterized constructor.
BST(int);
// Insert function.
BST* Insert(BST*, int);
// Inorder traversal.
void Inorder(BST*);
};
// Default Constructor definition.
BST ::BST()
: data(0)
, left(NULL)
, right(NULL)
{
}
// Parameterized Constructor definition.
BST ::BST(int value)
{
data = value;
left = right = NULL;
}
// Insert function definition.
BST* BST ::Insert(BST* root, int value)
{
if (!root) {
// Insert the first node, if root is NULL.
return new BST(value);
}
// Insert data.
if (value > root->data) {
// Insert right node data, if the 'value'
// to be inserted is greater than 'root' node data.
// Process right nodes.
root->right = Insert(root->right, value);
}
else if (value < root->data){
// Insert left node data, if the 'value'
// to be inserted is smaller than 'root' node data.
// Process left nodes.
root->left = Insert(root->left, value);
}
// Return 'root' node, after insertion.
return root;
}
// Inorder traversal function.
// This gives data in sorted order.
void BST ::Inorder(BST* root)
{
if (!root) {
return;
}
Inorder(root->left);
cout << root->data << endl;
Inorder(root->right);
}
xxxxxxxxxx
# Tree traversal in Python
class Node:
def __init__(self, item):
self.left = None
self.right = None
self.val = item
def inorder(root):
if root:
# Traverse left
inorder(root.left)
# Traverse root
print(str(root.val) + "->", end='')
# Traverse right
inorder(root.right)
def postorder(root):
if root:
# Traverse left
postorder(root.left)
# Traverse right
postorder(root.right)
# Traverse root
print(str(root.val) + "->", end='')
def preorder(root):
if root:
# Traverse root
print(str(root.val) + "->", end='')
# Traverse left
preorder(root.left)
# Traverse right
preorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Inorder traversal ")
inorder(root)
print("\nPreorder traversal ")
preorder(root)
print("\nPostorder traversal ")
postorder(root)
xxxxxxxxxx
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
xxxxxxxxxx
// Java program to demonstrate
// insert operation in binary
// search tree
class BinarySearchTree {
/* Class containing left
and right child of current node
* and key value*/
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
BinarySearchTree() { root = null; }
BinarySearchTree(int value) { root = new Node(value); }
// This method mainly calls insertRec()
void insert(int key) { root = insertRec(root, key); }
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null) {
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
else if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
// This method mainly calls InorderRec()
void inorder() { inorderRec(root); }
// A utility function to
// do inorder traversal of BST
void inorderRec(Node root)
{
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
// Driver Code
public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// print inorder traversal of the BST
tree.inorder();
}
}
// This code is contributed by Ankur Narain Verma
xxxxxxxxxx
//Java Binary Search Tree with In-Order, Pre-Order and Post-Order Traversals
public class BinarySearchTree {
public static void main(String[] args) {
searchSolution s = new searchSolution();
s.insertionkey('J');
s.insertionkey('B');
s.insertionkey('E');
s.insertionkey('C');
s.insertionkey('G');
s.insertionkey('A');
s.insertionkey('H');
s.insertionkey('I');
s.insertionkey('D');
s.insertionkey('F');
System.out.println("IN ORDER Search");
s.InOrderTraversal(s.root);
System.out.println();
System.out.println();
System.out.println("PRE ORDER Search");
s.PreOrderTraversal(s.root);
System.out.println();
System.out.println();
System.out.println("POST ORDER Search");
s.PostOrderTraversal(s.root);
}
}
class searchSolution {
node root;
void insertionkey(char key) {
root = insertionInTree(root, key);
}
node insertionInTree(node root, char key) {
if (root == null) {
root = new node(key);
return root;
}
if (key < root.key) {
root.left = insertionInTree(root.left, key);
} else if (key > root.key) {
root.right = insertionInTree(root.right, key);
}
return root;
}
void InOrderTraversal(node n) {
// InOrder Traversal = Left Root Right
if (n != null) {
InOrderTraversal(n.left);
System.out.print(n.key + " ");
InOrderTraversal(n.right);
}
}
void PreOrderTraversal(node n) {
// PreOrder Traversal = Root Left Right
if (n != null) {
System.out.print(n.key + " ");
PreOrderTraversal(n.left);
PreOrderTraversal(n.right);
}
}
void PostOrderTraversal(node n) {
// PostOrder Traversal = Left Right Root
if (n != null) {
PostOrderTraversal(n.left);
PostOrderTraversal(n.right);
System.out.print(n.key + " ");
}
}
}
class node {
char key;
node left, right;
node(char KEY) {
this.key = KEY;
}
}
xxxxxxxxxx
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
xxxxxxxxxx
//
// Created by merom on 5/10/2023.
//
#ifndef HOMEWORK_NO_SUBMISSION_BSTREE_H
#define HOMEWORK_NO_SUBMISSION_BSTREE_H
#include <memory>
#include <iostream>
#include <iostream>
#include <memory>
template<typename T>
struct Node {
T value;
std::unique_ptr<Node> left, right;
explicit Node(T val) : value(val), left(nullptr), right(nullptr) {}
};
template<typename T>
class BST {
public:
/*ctr's*/
BST() : _root(nullptr) {}
public:
/*Printing*/
void print_inorder();
void print_preorder();
void print_postorder();
public:
/* setter */
void insert(T && value){
insert_data(std::move(value));
}
void insert(T & value){
insert_data(value);
}
public:
/*Get value */
T find(const T& value) const {
auto val = find_helper(_root.get(), value);
return val->value;
}
public:
/*Remove*/
void remove(const T &data) {
remove_helper(_root, data) ;
}
public:
/*Delete the whole tree*/
void clear() {
clear_helper(_root);
}
public:
/*get _root */
const Node<T> * get_root() const { return _root.get(); }
private:
std::unique_ptr<Node<T>> _root;
private:
void print_helper(Node<T>*, char c ='i');
void insert_data(T && val);
void insert_data(T & val);
const Node<T> * find_helper(const Node<T> * node,const T& value) const ;
T get_min_value(const std::unique_ptr<Node<T>>& node);
void remove_helper(std::unique_ptr<Node<T>> & , const T & data);
private:
void clear_helper(std::unique_ptr<Node<T>>& node);
};
#endif //HOMEWORK_NO_SUBMISSION_BSTREE_H
#include "BSTree_impl.h"
xxxxxxxxxx
# Driver Code
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print ("Element is present at index % d" % result)
else:
print ("Element is not present in array")