Two nodes with given sum in binary search tree

Two nodes with a given sum in a binary search tree

Given a binary search tree and an integer k, find all two nodes with given sum, nodes (a,b) such that a+b =k. In other words, find two nodes in a binary search tree which add to a number. For example, in the binary search tree given below, if k = 24, node(5) and node(19) should be the result.

sum of two nodes

Two nodes with given sum in binary search tree: thoughts

We have solved a similar problem with arrays, where we had to find pairs with a given sum k, the basic idea was that if the array is sorted, we will scan it from start(moving right) and end(moving left), and see if elements at two ends add up to k. If the sum of those numbers is greater than k, we move to right from start. If the sum of those two numbers is less than k, we move to left from end. We continue till two pointers cross each other.

Is there a way in which binary search tree can be sorted array? Yes, if BST is traversed in inorder, output is in sorted order of nodes. So, if we scan the BST and store in an array, the problem is same as find pairs in an array with a given sum. 
However, the solution requires two scans of all nodes and additional space of O(n).

Another solution could be to use a hash map. Each node is stored in the hashmap and at each node, we check if there is a key (sum-node.value) present in the hashmap. If yes, then two nodes are added into the result set. This still requires additional space, however, there is only one traversal of the tree.

How can we avoid additional space? Look at the binary search tree property: all the nodes on the left subtree of a root node are less than and all the nodes on right subtree are greater than the root node.
We know that the minimum node in BST is the leftmost node and the maximum node is the rightmost node.
If we start an inorder traversal, the leftmost node is the first node to be visited and if we do a reverse inorder traversal, the rightmost node is the first node will be visited. If the sum of the minimum and the maximum is less than k, then we have to go to the second minimum (next node in forward inorder traversal). Similarly, if the sum of the minimum and the maximum is greater than k, then we have to go to the second maximum(next in reverse inorder traversal)

How can we do a forward and reverse inorder traversal at the same time? 

Sum of two nodes in binary search tree: stacks

We know how to traverse a tree using stack data structure. We will use two stacks, one stack stores the nodes to be visited in forward inorder traversal and second stores the nodes to be visited in reverse inorder traversal. When we reach the leftmost and the rightmost node, we pop from the stacks and check for equality with the given sum.
If the sum of the two nodes is less than k, we increase one of the nodes. We will go to the right subtree of the node popped from the forward inorder stack. Why? Because that’s where we will find the next greater element.

If the sum of the two nodes is greater than k, we decrease one of the nodes. We will go to the left subtree of the node popped from the reverse inorder stack. Why? Because that’s where we will find the next smaller element.

We will continue till both forward and reverse inorder traversal do not meet.

Two nodes with given sum in BST: Implementation

package com.company;

import com.company.BST.TreeNode;
import javafx.util.Pair;

import java.util.ArrayList;
import java.util.Stack;

/**
 * Created by sangar on 26.11.18.
 */
public class TwoNodesWithGivenSum {
    public ArrayList<Pair<Integer, Integer>>
		findPairsWithGivenSum(TreeNode root, int sum) {

        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();

        ArrayList<Pair<Integer, Integer>> result
			= new ArrayList<>();

        TreeNode cur1 = root;
        TreeNode cur2 = root;

        while (!s1.isEmpty() || !s2.isEmpty() ||
                cur1 != null || cur2 != null) {
            if (cur1 != null || cur2 != null) {
                if (cur1 != null) {
                    s1.push(cur1);
                    cur1 = cur1.getLeft();
                }

                if (cur2 != null) {
                    s2.push(cur2);
                    cur2 = cur2.getRight();
                }
            } else {
                int val1 = (int)s1.peek().getValue();
                int val2 = (int)s2.peek().getValue();

                if (s1.peek() == s2.peek()) break;

                if (val1 +  val2 == sum)
					result.add(new Pair(val1, val2)) ;

                if (val1 + val2 < sum) {
                    cur1 = s1.pop();
                    cur1 = cur1.getRight();
                } else {
                    cur2 = s2.pop();
                    cur2 = cur2.getLeft();
                }
            }
        }

        return result;
    }
}

Test cases

package test;

import com.company.BST.BinarySearchTree;
import com.company.TwoNodesWithGivenSum;
import javafx.util.Pair;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Created by sangar on 23.9.18.
 */
public class TwoNodesWithGivenSumTest {

    TwoNodesWithGivenSum tester = new TwoNodesWithGivenSum();

    @Test
    public void twoNodesWithGivenSumTest() {

        BinarySearchTree<Integer> binarySearchTree
			= new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        ArrayList<Pair<Integer, Integer>> result
			= new ArrayList<>();
        result.add(new Pair(12,15));

        assertEquals(result, 
			tester.findPairsWithGivenSum(
				binarySearchTree.getRoot(),
				27
			)
		);
    }

    @Test
    public void twoNodesWithGivenSumNotPossibleTest() {

        BinarySearchTree<Integer> binarySearchTree
			= new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        ArrayList<Pair<Integer, Integer>> result 
			= new ArrayList<>();
        assertEquals(result,
			tester.findPairsWithGivenSum(
				binarySearchTree.getRoot(),
				45
			)
		);
	}

    @Test
    public void twoNodesWithGivenSumNullTreeTest() {

        ArrayList<Pair<Integer,Integer>> result
			= new ArrayList<>();

        System.out.println(result);

        assertEquals(result,
			tester.findPairsWithGivenSum(
				null,
				45
			)
		);
    }
}

The complexity of this method to find two nodes with a given sum in a binary search tree is O(n). We are storing nodes in stacks, which will have space complexity of O(n), however, it is less than the previous solutions as it actually making the recursive stack explicit.

Please share if you have any doubts or something is missing or wrong. If you are preparing for an interview, signup to receive a free interview kit.

Lowest common ancestor in binary tree

Lowest common ancestor (LCA) in BST

Given a binary search tree and two nodes, find the lowest node which is the parent of both given nodes, that is the lowest common ancestor (LCA). For example, in the following tree, LCA of 6 and 1 is node(5), whereas lowest common ancestor of node 17 and 6 would be node(10).

lowest common ancestor lca

Lowest common ancestor : Thoughts

What is the condition for a node to be LCA of two nodes?  If paths for given nodes diverges from the node, then node is lowest common ancestor. While path is common for both the nodes, nodes are common ancestor but they are not lowest or least. How can we find where paths are diverging?

Paths are diverging when one node is on left subtree and another node is on right subtree of the node. Brute force solution would be to find one node and then go up the tree and see at what parent node, other given node falls on the opposite subtree.

Implementation wise, traverse to node 1 and node 2 and store both paths on the stack. Then pop from two stacks till you find the same node on both paths, that node would be the lowest common ancestor. There will be two scans of the tree and additional space complexity to store paths which in the worst case be O(n).

However, the brute force solution does not use the property of a binary search tree. Property is that all the nodes on the left side of a node are smaller and all the nodes on the right side of a node are greater than node. Can we use that property to solve this problem?

Basic idea is to return the node if it is found in any of the subtrees. At any node, search for both given nodes in the left subtree.  If we get a non-empty node returned from the left subtree, there is at least one of the two nodes is on left subtree.

Again, search in right subtree these two nodes, if a non-empty node is returned from the right subtree, that means at least one of the node is on right subtree.

What does it means if we have a non-empty node on both left and right subtree? It means two nodes are on the left and right subtree, one on each side. It means the root node is the lowest common ancestor.

What if one of the returned nodes is empty? It means both nodes are on one side of the root node, and we should return the upwards the non-empty node returned.

Let’s take an example and see how does it work? Given the below tree, find the lowest common ancestor of node(1) and node(9).

lowest common anestor in binary tree

Start with the node(10) and look for the left subtree for both node(1) and node(9). Go down all the way to the node(1), at the time, we return 1 as the node as node.value is equal to one of the nodes.

lowest common anestor in binary tree

lowest common anestor in binary treeAt node(5), we have got node(1) return from left subtree. We will search for node(1) and node(9) on right subtree. We go all the way to node(6), which is leaf node.

least common ancestor in binary search tree

At node(8), left subtree returns nothing as none of the nodes in the left subtree of node(8). However, right subtree returns node(9).

lowest common ancestor

As per our algorithm, if either of subtree returns non-empty node, we return the node return from the subtree.

lca in binary search tree

At node(5), we get a non-empty node from right subtree and we already know, from the left subtree, we got node(1). At this point at node(5), we have both left and right subtree returning non-empty node, hence return the node(5).

lca in binary treee

Two nodes will be searched on the right subtree of node(10), which will return nothing, hence, final lowest common ancestor will be node(5).

Lowest common ancestor : Implementation

#include<stdio.h>
#include<stdlib.h>
 
struct node{
	int value;
	struct node *left;
	struct node *right;
};

typedef struct node Node;

Node * findLCA(Node *root, int val1, int val2)
{
    // Base case
    if (root == NULL) return NULL;
 
    /* If either val1 or val2 matches with root's key, 
       report the presence by returning the root
       (Note that if a key is the ancestor of other,
       then the ancestor key becomes LCA 
   */
    if (root->key == val1 || root->key == val2)
        return root;
 
    // Look for keys in left and right subtrees
    Node *left  = findLCA(root->left, val1, val2);
    Node *right = findLCA(root->right, val1, val2);
 
    /* If both of the above calls return Non-NULL,
       then one key is present in once subtree
       and other is present in other,
       So this node is the LCA */
    if (left && right)  return root;
 
    // Otherwise check if left subtree or right subtree is LCA
    return (left != NULL)? left : right;
}

Node * createNode(int value){
  Node *newNode =  (Node *)malloc(sizeof(Node));
  
  newNode->value = value;
  newNode->right= NULL;
  newNode->left = NULL;
  
  return newNode;
}

Node * addNode(Node *node, int value){
  if(node == NULL){
      return createNode(value);
  }
  else{
     if (node->value > value){
        node->left = addNode(node->left, value);
      }
      else{
        node->right = addNode(node->right, value);
      }
  }
  return node;
}
 
/* Driver program for the function written above */
int main(){
  Node *root = NULL;
  //Creating a binary tree
  root = addNode(root,30);
  root = addNode(root,20);
  root = addNode(root,15);
  root = addNode(root,25);
  root = addNode(root,40);
  root = addNode(root,37);
  root = addNode(root,45);
  
  printf("\n least common ancestor: %d ",
      leastCommonAncestor(root, 15, 25));
  
  return 0;
}

Below implementation only works for binary search tree and not for the binary tree as above method works.

#include<stdio.h>
#include<stdlib.h>
 
struct node{
	int value;
	struct node *left;
	struct node *right;
};

typedef struct node Node;

int leastCommonAncestor(Node *root, int val1, int val2){

 	if(!root)
       return -1;

 	if(root->value == val1 || root->value == val2)
    	return root->value;

 	/* Case 3: If one value is less and other greater
             than the current node
             Found the LCS return */
 	if((root->value > val1 && root->value <= val2) ||
  		(root->value <= val1 && root->value >val2)){
             return root->value;
 	}
  	/*Case 2 : If Both values are greater than current node, 
           look in right subtree */
 	else if(root->value < val1 && root->value <val2){
        return leastCommonAncestor(root->right, val1, val2);
 	}
 	/*Case 1 : If Both values are less than current node,
           look in left subtree */
 	else if(root->value > val1 && root->value > val2){
        return leastCommonAncestor(root->left, val1, val2);
 	}
}

Node * createNode(int value){
  Node *newNode =  (Node *)malloc(sizeof(Node));
  
  newNode->value = value;
  newNode->right= NULL;
  newNode->left = NULL;
  
  return newNode;
  
}

Node * addNode(Node *node, int value){
  if(node == NULL){
      return createNode(value);
  }
  else{
     if (node->value > value){
        node->left = addNode(node->left, value);
      }
      else{
        node->right = addNode(node->right, value);
      }
  }
  return node;
}
 
/* Driver program for the function written above */
int main(){
  Node *root = NULL;
  //Creating a binary tree
  root = addNode(root,30);
  root = addNode(root,20);
  root = addNode(root,15);
  root = addNode(root,25);
  root = addNode(root,40);
  root = addNode(root,37);
  root = addNode(root,45);
  
  printf("\n least common ancestor: %d ",
      leastCommonAncestor(root, 15, 25));
  
  return 0;
}

The worst complexity of the algorithm to find the lowest common ancestor in a binary tree is O(n). Also, keep in mind that recursion is involved. More skewed the tree, more stack frames on the stack and more the chances that stack will overflow.

This problem is solved using on traversal of tree and managing states when returning from recursive calls.

Please share if there is something wrong or missing. If you are willing to contribute and share your knowledge with thousands of learners across the world, please reach out to us at communications@algorithmsandme.com

Find Kth smallest element in binary search tree

Kth smallest element in a binary a search tree

Given a binary search tree, find kth smallest element in the binary search tree. For example, 5th smallest element in below binary search tree would be 14, if store the tree in sorted order 5,7,9,10,14,15,19; 14 is the fifth smallest element in that order.

kth smallest element in binary search tree
Kth smallest element in binary search tree

Kth smallest element in binary search tree: thoughts

As mentioned earlier in a lot of posts like delete a binary tree or mirror a binary tree, first try to find the traversal order required to solve this problem. One hint we already got is that we want all the nodes on BST traversed in sorted order. What kind of traversal gives us a sorted order of nodes? Of course, it is inorder traversal.

So idea is to do an inorder traversal of the binary search tree and store all the nodes in an array. Once traversal is finished, find the kth smallest element in the sorted array.

This approach, however, scans the entire tree and also has space complexity of O(n) because we store all the nodes of tree in an array. Can we avoid scanning the whole tree and storing nodes?

If we keep count of how many nodes are traversed during inorder traversal, we can actually stop traversal as soon as we see k nodes are visited. In this case, we do not store nodes, just a counter. 

Kth smallest element in binary tree: implementation

package com.company.BST;

import java.util.Stack;

/**
 * Created by sangar on 9.11.18.
 */
public class FindKthSmallestInBST {
    private int counter;

    public FindKthSmallestInBST(){
        counter = 0;
    }
    public TreeNode findKthSmallest(TreeNode root, int k){
        if(root == null) return root;

        //Traverse left subtree first
        TreeNode left = findKthSmallest(root.getLeft(),k);
        //If we found kth node on left subtree
        if(left != null) return left;
        //If k becomes zero, that means we have traversed k nodes.
        if(++counter == k) return root;

        return findKthSmallest(root.getRight(),k);
    }
}

Test cases

package test;

import com.company.BST.BinarySearchTree;
import com.company.BST.FindKthSmallestInBST;
import com.company.BST.TreeNode;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * Created by sangar on 23.9.18.
 */
public class KthSmallestElementTest {

    FindKthSmallestInBST tester = new FindKthSmallestInBST();

    @Test
    public void kthSmallestElementTest() {

        BinarySearchTree<Integer> binarySearchTree =
			new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        TreeNode kthNode =
			tester.findKthSmallest(binarySearchTree.getRoot(),1);
        assertEquals(6, kthNode.getValue());
    }

    @Test
    public void kthSmallestElementOnRightSubtreeTest() {

        BinarySearchTree<Integer> binarySearchTree =
				new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        TreeNode kthNode =
			tester.findKthSmallest(binarySearchTree.getRoot(),5);
        assertEquals(12, kthNode.getValue());
    }

    @Test
    public void kthSmallestElementAbsentSubtreeTest() {

        BinarySearchTree<Integer> binarySearchTree =
				new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        TreeNode kthNode =
			tester.findKthSmallest(binarySearchTree.getRoot(),10);
        assertEquals(null, kthNode);
    }

    @Test
    public void kthSmallestElementNulltreeTest() {

        BinarySearchTree<Integer> binarySearchTree =
				new BinarySearchTree<>();
        binarySearchTree.insert(10);
        binarySearchTree.insert(8);
        binarySearchTree.insert(15);
        binarySearchTree.insert(12);
        binarySearchTree.insert(6);
        binarySearchTree.insert(9);

        TreeNode kthNode = tester.findKthSmallest(null,10);
        assertEquals(null, kthNode);
    }
}

The complexity of this algorithm to find kth smallest element is O(k) as we traverse only k nodes on binary search tree.

There is hidden space complexity here. Recursive function requires call stack memory, which is limited to Operation System default. More deep you go in recursion, more space we use on stack. If tree is completely skewed, there are more chances of stack overflow. Also recursive function is very difficult to debug in production environments. Below is the non-recursive solution for the same problem.

Non-recursive way to find kth smallest element in BST

public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> s = new Stack<TreeNode>();

        TreeNode current = root;
        int result = 0;

        while(!s.isEmpty() || current!=null){
            if(current!=null){
                s.push(current);
                current = current.getLeft();
            }else{
                TreeNode  temp = s.pop();
                k--;
                if(k==0)
                    result = (int)temp.getValue();
                current = temp.getRight();
            }
        }

        return result;
    }

Please share if there is something wrong or missing. If you are preparing for an interview and need help, please reach out to us at communications@algorithmsandme.com