Check if a Binary Tree is Binary Search Tree

Given a Binary Tree, write code to check if it is Binary Search Tree or not ? Binary search tree is a binary tree with following restrictions All values in the left subtree are Less than the value at root. All values in the Right subtree are Greater than the value at root. Both Left […]

Convert a Binary Tree to Binary Search Tree

Given a Binary Tree, write code to convert it to Binary Search Tree such that the structure of the tree remains the same. For example: Both the below trees 5 10 / \ / \ 8 10 5 30 / \ \ / \ \ 4 30 1 8 40 1 / / 40 4 […]

Speed and time question

Two towns are exactly 100 km apart. Suresh leaves City-A at 3 pm driving at 30 km/hr. After 30 minutes, at 3:30 pm, Ramesh leaves City-B driving at 60 km/hr. When they meat each other, how far they will be from City-A ?

Lowest Common Ancestor in Binary Search Tree

In a Binary Search Tree, you are given the values of two nodes. Write a code which will return the Lowest Common Ancestor of both the nodes. For Example: If the BST is as shown on the right and Nodes are 4 and 8, The output should be: 5 4 and 8 has two common […]

Number of nodes in a binary tree

Write a function which will return the total number of nodes in a Binary tree. For example, the Binary tree on the right has 7 nodes.

Kadane's Algorithm to find maximum subarray sum

Given an array of n integers (both +ve and -ve). Find the contiguous sub-array whose sum is maximum (More than 1 sub-array may have same sum). For Example: Array Maximum Sub-Array sum ———————– ———————– —- {5, 7, 12, 0, -8, 6} {5, 7, 12} 24 {6, -2, -3, 4, -1, 10 } {6, -2, -3, […]

check if all nodes of a tree has only one child

Given the PreOrder traversal of a binary search tree (in the form of a tree), check if all the nodes (except the last) of the tree has exactly one child. For Example: If the Preorder traversal of the tree is given as below: {50, 25, 45, 30, 27, 29} The the output should be: TRUE […]

Detecting loop in a linked list

Given a Singly linked list which may contain a loop (link of last node pointing to some Node in the list). Write code to detect the loop.