print all nodes at a distance of 'x' from a given node in BST - algorithm

The detailed question is to find all the nodes with distance x( i.e. number of edges =x) from a given node .
I was asked in an Amazon Interview today,
void findNodeWithDistanceX(struct node* root,struct node * qnode, int value)
{
//root is root Node, qnode is questionnode from which distance to be calculated, value is the
//distance to be calculated
//finding distance between root and qnode
int distance = findDistancefromRoot(root ,qnode);
if(distance> value)
{
traverseDistancedown(root ,distance-value);
}
if(distance ==value){
printf("%d",root->value);
}
// Traverse and find all nodes with distance value from 'qnode' down the tree
traverseDistancedown(qnode,value);
Now In case of finding the distance "value" from qnode .
I did not get the answer how to traverse up the Tree and satisfy the condition of distance with value.
Although many cases arises here.
I tried backtracking from qnode but to no avail I was unable to impress him and unable to write the Code.
Any Discussion regarding implementing the traversal up the tree will be helpful to me.

The simplest way is with a depth-first search, keeping track of the distance as you go along. It's a simple pre-order traversal starting at the "question node".
void nodesAtDistance(struct node* qnode, int requestedDistance, int currentDistance)
{
if (qnode == null) return;
if (currentDistance == requestedDistance)
{
// output qnode
// and then return because children are further away
return;
}
// visit left and then right
nodesAtDistance(qnode->left, requestedDistance, currentDistance+1);
nodesAtDistance(qnode->right, requestedDistance, currentDistance+1);
}
So if you call this with:
nodesAtDistance(myNode, 5, 0);
It will output all nodes that are 5 levels below myNode.
Now, if I were to write this as an API function, I would provide an overload that doesn't require the client to pass that currentDistance parameter. Because if somebody were to write nodesAtDistance(myNode, 5, 1), you'd get things at distance 4. So, create this overload:
void nodesAtDistance(node * qnode, int requestedDistance)
{
nodesAtDistance(qnode, requestedDistance, 0);
}
Make that function publicly visible, and make the other one private.

try this code, although this code checks only for children nodes and does not go back to check on ancestors nodes at given distance
#include<stdio.h>
#include<malloc.h>
struct treenode
{
unsigned int data;
struct treenode *left;
struct treenode *right;
};
struct treenode *treeptr, *sourcenode, *quesnode, *quesleftnode, *quesrightnode, *root = NULL;
struct node *treeptr insert_node(unsigned int treedata)
{
treeptr= (struct node*)(malloc(sizeof(treenode)));
treeptr->data = nodevalue;
treeptr->left = NULL;
treeptr->right = NULL;
return treeptr;
}
printnodesdistancek(struct treenode* quesnode, unsigned char reqdist)
{
unsigned char curdist=0;
do
{
if(quesnode == null)
return;
quesleftnode = quesnode->left;
if(curdist == reqdist)
{
printf("%d",quesleftnode->data);
}
else
{
quesnode= quesnode->left;
}
quesrightnode = quesnode->right;
if(curdist == reqdist)
{
printf("%d",quesrightnode->data);
}
else
{
quesnode = quesnode->right;
}
}while(quesnode!=NULL);
//main function
void main(void)
{
//create tree
*root = insert_node(1);
root->left=insert_node(-1);
root->right=insert_node(2);
root->left->left=insert_node(-2);
root->left->right=insert_node(3);
root->right->left=insert_node(-3);
root->right->right=insert_node(4);
sourcenode = root->left;
printnodesdistancek(sourcenode,1);
}

Related

SINGLE Recursive function for Print/Fetch kth smallest element in Binary search tree

I am trying to print the kth smallest element in an BST.
The first solution is using in-order traversal.
Next solution is finding the index of the current node by calculation the size of its left subtree.
Complete algo:
Find size of left subtree:
1.If size = k-1, return current node
2.If size>k return (size-k)th node in right subtree
3.If size<k return kth node in left subtree
This can be implemented using a separate count function which looks something like
public class Solution {
public int kthSmallest(TreeNode root, int k) {
//what happens if root == null
//what happens if k > total size of tree
return kthSmallestNode(root,k).val;
}
public static TreeNode kthSmallestNode(TreeNode root,int k){
if(root==null) return root;
int numberOfNodes = countNodes(root.left);
if(k == numberOfNodes ) return root;
if(k<numberOfNodes ) return kthSmallestNode(root.left,k);
else return kthSmallestNode(root.right,k-numberOfNodes );
}
private static int countNodes(TreeNode node){
if(node == null) return 0;
else return 1+countNodes(node.left)+countNodes(node.right);
}
}
But I see that we count the size for same trees multiple times, so one way is to maintain an array to store thes sizes like the DP way.
But I want to write a recursive solution for this.And here is the code I have written.
class Node {
int data;
Node left;
Node right;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
}
}
public class KthInBST
{
public static Node createBST(int headData)
{
Node head = new Node(headData, null, null);
//System.out.println(head.data);
return head;
}
public static void insertIntoBst(Node head, int data)
{
Node newNode = new Node(data, null, null);
while(true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static void main(String[] args)
{
Node head = createBST(5);
insertIntoBst(head, 7);
insertIntoBst(head, 6);
insertIntoBst(head, 2);
insertIntoBst(head, 1);
insertIntoBst(head, 21);
insertIntoBst(head, 11);
insertIntoBst(head, 14);
insertIntoBst(head, 3);
printKthElement(head, 3);
}
public static int printKthElement(Node head, int k)
{
if (head == null) {
return 0;
}
int leftIndex = printKthElement(head.left, k);
int index = leftIndex + 1;
if (index == k) {
System.out.println(head.data);
} else if (k > index) {
k = k - index;
printKthElement(head.right, k);
} else {
printKthElement(head.left, k);
}
return index;
}
}
This is printing the right answer but multiple times, I figured out why it is printing multiple times but not understanding how to avoid it.
And also If I want to return the node instead of just printing How do I do it?
Can anyone please help me with this?
Objective:
Recursively finding the kth smallest element in a binary search tree and returning the node corresponding to that element.
Observation:
The number of elements smaller than the current element is the size of the left subtree so instead of recursively calculating its size, we introduce a new member in class Node, that is, lsize which represents the size of the left subtree of current node.
Solution:
At each node we compare the size of left subtree with the current value of k:
if head.lsize + 1 == k: current node in our answer.
if head.lsize + 1 > k: elements in left subtree are more than k, that is, the k the smallest element lies in the left subtree. So, we go left.
if head.lsize + 1 < k: the current element alongwith all the elements in the left subtree are less than the kth element we need to find. So, we go to the right subtree but also reduce k by the amount of elements in left subtree + 1(current element). By subtracting this from k we make sure that we have already taken into account the number of elements which are smaller than k and are rooted as the left subtree of current node (including the current node itself).
Code:
class Node {
int data;
Node left;
Node right;
int lsize;
public Node(int data, Node left, Node right) {
this.left = left;
this.data = data;
this.right = right;
lsize = 0;
}
}
public static void insertIntoBst(Node head, int data) {
Node newNode = new Node(data, null, null);
while (true) {
if (data > head.data) {
if (head.right == null) {
head.right = newNode;
break;
} else {
head = head.right;
}
} else {
head.lsize++; //as we go left, size of left subtree rooted
//at current node will increase, hence the increment.
if (head.left == null) {
head.left = newNode;
break;
} else {
head = head.left;
}
}
}
}
public static Node printKthElement(Node head, int k) {
if (head == null) {
return null;
}
if (head.lsize + 1 == k) return head;
else if (head.lsize + 1 > k) return printKthElement(head.left, k);
return printKthElement(head.right, k - head.lsize - 1);
}
Changes:
A new member lsize has been introduced in class Node.
Slight modification in insertIntoBst.
Major changes in printKthElement.
Corner case:
Add a check to ensure that k is between 1 and the size of the tree otherwise a null node will be returned resulting in NullPointerException.
This is working on the test cases I have tried, so far. Any suggestions or corrections are most welcome.
:)

I need to design an algorithm to return the number of nodes in a binary tree that have two children

I have come across this question to design an algorithm to count the number of nodes in a binary tree that has two children. It was mentioned that the solution should be expressed as a pair of functions(not BST member functions).
So far I could not arrive at a concrete solution and specially the part where the solution should be expressed as a pair of non BST member functions is going over my head.
//count the number of node that has got 2 children
function countNodes(nodeElement,nodeNumber){
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
//check if current node has got two childs
if(getNodeChildren(children[c])==2){
nodeNumber++;
}
//recursively check if children nodes has got 2 children
nodeNumber += countNodes(children[c],nodeNumber)
}
return nodeNumber;
}
//recursively counts the number of children that a node has got
function getNodeChildren(nodeElement){
//check if is a leaf
if(nodeElement.children == 0){
return 1;
}
else {
var nodeNumber = 0;
var children = nodeElement.children;
for(var c=0;c<children ;c++){
nodeNumber += getNodeChildren(children[c],nodeNumber+1);
}
return nodeNumber;
}
}
Assuming Node is a struct containing two pointers to Node, named left and right:
int count_2_ch_nodes(Node* root)
{
if (root == NULL) return 0;
// Recursively count the number of nodes that are below
// this node that have two children:
int count = 0;
if (root->left != NULL) count += count_2_ch_nodes(root->left);
if (root->right != NULL) count += count_2_ch_nodes(root->right);
// Add this node IF it has 2 children:
if (has_2_ch(root)) count++;
return count;
}
/* Returns TRUE if node has two children */
int has_2_ch(Node* node)
{
return (node->left != NULL && node->right != NULL);
}
This is the complete java code for your question.
import java.util.ArrayList;
import java.util.Scanner;
/*
* Creating datastructure for Node
* Every Node contains data given by user and leftChild and rightChild childs
* Left and rightChild childs are automatically assigned by the program
*/
class Node
{
Node leftChild, rightChild;
String data;
/*
* Assigning leftChild , rightChild and data to the node using a constructor
*/
Node(Node left, Node right, String data)
{
this.leftChild =left;
this.rightChild =right;
this.data=data;
}
}
public class FirstAnswer {
/*
* Initializing the count for number of nodes
*/
private static int count=0;
private static int numberOfNodes(Node root)
{
/*
* Writing the base case for the recursive function
* If leftChild or rightChild or both are null it returns 0 as no childs are present
*/
if ((root.leftChild ==null && root.rightChild ==null) || (root.leftChild ==null) || (root.rightChild ==null))
return 0;
else {
count+=2;
Node left=root.leftChild;
Node right=root.rightChild;
/*
* Calling the recursive function twice by making leftChild child and rightChild child of root as root
*/
System.out.println(root.data+" : "+"\n"+"Left child : "+left.data+"\n"+"Right child : "+right.data);
numberOfNodes(left);
numberOfNodes(right);
}
return count+1; //Since root node is not counted
}
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
/*
* Creating individual nodes with string data from user
* Holding them in an array list inputs
*/
ArrayList<Node> inputs=new ArrayList<>();
String status="Y";
System.out.print("Enter data for root node : ");
inputs.add(new Node(null,null,sc.next()));
while (status.equals("Y") || status.equals("y"))
{
if (inputs.size()%2==1)
{
for (int j=0;j<2;j++)
{
System.out.print("data for child "+(j+1)+" : ");
inputs.add(new Node(null,null,sc.next()));
}
/*
* Yes or No for adding more number of nodes
*/
System.out.println("Press Y or y if more inputs have to be given else press N to construct tree with given inputs...");
status=sc.next();
}
}
Node[] tree=new Node[inputs.size()];
/*
* Above is the tree which is being constructed from the nodes given by user
*/
for (int i=inputs.size()-1;i>=0;i--)
{
int j=i+1;
/*
* Making tree format by locating childs with indices at 2*p and 2*p+1
*/
if ((2*j+1)<=inputs.size())
{
tree[i]=new Node(tree[2*i+1],tree[2*i+2],inputs.get(i).data);
}
else {
tree[i]=inputs.get(i);
}
}
/*
* Calling the recursive function to count number of nodes
* Since first node is the root we start from here
*/
System.out.println(numberOfNodes(tree[0]));
}
}
Hope this helps you ;)

finding depth of a tree?

I am very new to binary tree and recursion. My program is to find the height of the tree but I am a bit confused as to why my program doesn't work.
struct Node {
int value;
Node *left;
Node *right;
}
int heightOfTree(Node node){
if(node ==NULL)
{
return 0;
}
else
{
int lheight=heightOfTree(node->left);
int rheight = heightOfTree(node->right);
if(lheight>rheight)
{
return lheight;
}
else
{
return rheight;
}
}
}
I followed a pseudocode online so I implemented it myself because I don't want to just copy and paste. I tried to insert a lot of nodes but When I run my program I always get 0 height? Thank you
return lheight + 1;
and
return rheight + 1;
You need to increment the height at each level.

Iterative Threaded Binary Tree Traversing with only constant extra space

How to traverse a threaded binary tree non recursively in O(n) without using a stack (just allowed to use constant extra space for temp variables, so we can't add visit flag to each node in the tree). I spent a good time thinking about it but it just doesn't seem to me to be doable unless we are going to traverse the memory locations that have the tree data. Let's say that we are using multiple array representation to implement pointers, then we can traverse the tree in O(n), does anyone have something else in mind?
Note This is not homework, just to save the energy of some keyboard strokes to write comments about homework!
Let's say that we have the following threaded tree representation in C:
typedef struct threaded_binary_tree {
int value;
// Flag that tells whether right points to a right child or to a next
// node in inorder.
bool right_is_child;
struct threaded_binary_tree *left, *right;
} threaded_binary_tree;
Then, traversing it in O(1) memory may look like this:
void inorder(threaded_binary_tree *node)
{
threaded_binary_tree *prev = NULL;
// Ignore empty trees
if (node == NULL)
return;
// First, go to the leftmost leaf of the tree
while (node->left != NULL)
node = node->left;
while (node != NULL) {
// Nodes are visited along going upward in the tree
printf("%d\n", node->value);
prev = node;
node = node->right;
if (prev->right_is_child) {
// We're descending into tree
if (node != NULL) {
// Again, go to the leftmost leaf in this subtree
while (node->left != NULL)
node = node->left;
}
}
// else, we're climbing up in the tree
}
}
Warning: I haven't run this code.
This is the code written in Java:
public void inOrder() {
Node<T> curr = root;
boolean visited = false; //I haven't come across the node from which I came
while (curr != null) {
if (!visited && curr.left != null) { //Go to leftmost node
curr = curr.left;
} else {
System.out.println(curr.head + " ");
if (curr.right != null) { //I prioritize having childs than "threaded sons"
curr = curr.right;
visited = false;
} else {
curr = curr.rightThreaded;
visited = true; //Means that I will come back to a node I've already looped, but now i'll print it, except if i'm at the last node
}
}
}
}
Node is an inner class of ThreadedBinaryTree:
private static class Node<T> {
private T head;
private Node<T> left;
private Node<T> right;
private Node<T> leftThreaded;
private Node<T> rightThreaded;
public Node(T head, Node<T> leftThreaded, Node<T> rightThreaded) {
this.head = head;
this.leftThreaded = leftThreaded;
this.rightThreaded = rightThreaded;
}
}

binary tree construction from preorder

This is an Amazon interview question. Can any one give an algorithm to do this?
There is a binary tree with the following properties:
All of its inner node have the value 'N', and all the leaves have the value 'L'.
Every node either has two children or has no child.
Given its preorder, construct the tree and return the root node.
Since it is guaranteed that each internal node has exactly 2 children, we can simply build the tree recursively using that.
We call our function with the input provided, and it examines the first character it got. If it is a leaf node, it just returns a leaf. If it is an internal node, it just calls itself for the left and right subtrees and returns the tree formed using the node as root and the left and right subtrees as its left and right children.
Code follows (in Python). Note, I am using tuples to represent node, so the tree is a tuple of tuples.
#! /usr/bin/env python
from collections import deque
def build_tree(pre_order):
root=pre_order.popleft()
if root=='L':
return root
else:
return (root,build_tree(pre_order),build_tree(pre_order))
if __name__=='__main__':
print build_tree(deque("NNLLL"))
Edit: Code in Java
import java.util.*;
class Preorder{
public static Node buildTree(List<Character> preorder){
char token=preorder.remove(0);
if (token=='L'){
return new Node(token,null,null);
}
else{
return new Node(token,buildTree(preorder),buildTree(preorder));
}
}
public static void main(String args[]){
List<Character> tokens=new LinkedList<Character>();
String input="NNLLL";
for(int i=0;i<input.length();i++) tokens.add(input.charAt(i));
System.out.println(buildTree(tokens));
}
}
class Node{
char value;
Node left,right;
public Node(char value, Node left, Node right){
this.value=value;
this.left=left;
this.right=right;
}
public String toString(){
if (left==null && right==null){
return "("+value+")";
}
else{
return "("+value+", "+left+", "+right+")";
}
}
}
I can think of a recursive algorithm.
head = new node.
remove first character in preorderString
Invoke f(head, preorderString)
Recursive function f(node, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeLeft, attach to node, invoke f(nodeLeft, s)
- remove first char from s, if L then attach to node as leaf.
else create a nodeRight, attach to node, invoke f(nodeRight, s)
I think the key point is to realize that there are three possibilities for the adjacent nodes: NN, NL?, L? (``?'' means either N or L)
NN: the second N is the left child of the first N, but we don't know what the right child of the first N is
NL?: the second N is the left child of the first N, and the right child of the first N is ?
L?: ? is the right child of STACK top
A STACK is used because when we read a node in a preorder sequence, we don't know where its right child is (we do know where its left child is, as long as it has one). A STACK stores this node so that when its right child appears we can pop it up and finish its right link.
NODE * preorder2tree(void)
{
NODE * head = next_node();
NODE * p = head;
NODE * q;
while (1) {
q = next_node();
if (!q)
break;
/* possibilities of adjacent nodes:
* NN, NL?, L?
*/
if (p->val == 'N') {
p->L = q;
if (q->val == 'N') { /* NN */
push(p);
p = q;
} else { /* NL? */
q = next_node();
p->R = q;
p = q;
}
} else { /* L? */
p = pop();
p->R = q;
p = q;
}
}
return head;
}
The code above was tested using some simple cases. Hopefully it's correct.
Here is the java program::
import java.util.*;
class preorder_given_NNNLL
{
static Stack<node> stk = new Stack<node>();
static node root=null;
static class node
{
char value;
node left;
node right;
public node(char value)
{
this.value=value;
this.left=null;
this.right=null;
}
}
public static node stkoper()
{
node posr=null,posn=null,posl=null;
posr=stk.pop();
if(stk.empty())
{
stk.push(posr);
return null;
}
else
posl=stk.pop();
if(stk.empty())
{
stk.push(posl);
stk.push(posr);
return null;
}
else
{
posn=stk.pop();
}
if( posn.value == 'N' && posl.value == 'L' && posr.value == 'L')
{
root = buildtree(posn, posl, posr);
if(stk.empty())
{
return root;
}
else
{
stk.push(root);
root=stkoper();
}
}
else
{
stk.push(posn);
stk.push(posl);
stk.push(posr);
}
return root;
}
public static node buildtree(node posn,node posl,node posr)
{
posn.left=posl;
posn.right=posr;
posn.value='L';
return posn;
}
public static void inorder(node root)
{
if(root!=null)
{
inorder(root.left);
if((root.left == null) && (root.right == null))
System.out.println("L");
else
System.out.println("N");
inorder(root.right);
}
}
public static void main(String args[]){
String input="NNNLLLNLL";
char[] pre = input.toCharArray();
for (int i = 0; i < pre.length; i++)
{
node temp = new node(pre[i]);
stk.push(temp);
root=stkoper();
}
inorder(root);
}
}
The construct function does the actual tree construction. The code snippet is the solution for the GeeksforGeeks question that you mentioned as above.
struct Node*construct(int &index, Node*root, int pre[], int n, char preLN[])
{
Node*nodeptr;
if(index==n)
{
return NULL;
}
if(root==NULL)
{
nodeptr = newNode(pre[index]);
}
if(preLN[index]=='N')
{
index = index+1;
nodeptr->left = construct(index, nodeptr->left, pre,n,preLN);
index = index+1;
nodeptr->right = construct(index, nodeptr->right,pre,n,preLN);
return nodeptr;
}
return nodeptr;
}
struct Node *constructTree(int n, int pre[], char preLN[])
{
int index =0;
Node*root = construct(index,NULL,pre,n,preLN);
return root;
}
Points to Note:
Index has been declared a reference variable so that on returning back to the parent node, the function starts constructing the tree from the overall most recent value of index and not the value of index as possessed by the function when initially executing the call.
Different values of index for right and left subtrees since preorder traversal follows Root, Left ,Right sequence of nodes.
Hope it Helps.

Resources