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

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 ;)

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.
:)

finding second smallest element in binary search tree

int secondSmallestInBST(struct node * tNode) {
if( tNode==NULL || (tNode->left==NULL && tNode->right==NULL) ) // case 1 and 2
exit;
if(tNode->left == NULL){ // case 3
tNode=tNode->right;
while(tNode->left!=NULL){
tNode=tNode->left;
}
return tNode->data;
} // general case.
node * parent=tNode,* child = tNode->left;
while(child->left!=NULL){
parent = child;
child = child->left;
}
return parent->data;
}
not every test cases are passed for my code. suggest me if there is any test case missing in my code. i'm just finding the second smallest element in binary search tree.
int secondSmallestInBST(struct node * tNode) {
if( tNode==NULL || (tNode->left==NULL && tNode->right==NULL) ) // case 1 and 2
exit;
if(tNode->left == NULL){ // case 3
tNode=tNode->right; // find smallest in right bst.
while(tNode->left!=NULL){
tNode=tNode->left;
}
return tNode->data;
} // general case.
if(tNode->left->left==NULL && tNode->left->right!=NULL){ //missed case.
tNode=tNode->left->right;
while(tNode->left!=NULL){
tNode=tNode->left;
}
return tNode->data;
}
node * parent= tNode;
node * child = tNode->left;
while(child->left!=NULL){
parent = child;
child = child->left;
}
return parent->data;
}
//still missing some test cases in this code.
Test for this case - 3 6 2 3.
Tree will look like this :
6
/
2
\
3
The way you are doing, answer will come out to be 6, whereas it is 3.
`
int Successor(Node* root){
while(root->left){
root = root->left;
}
return root->data;
}
int Second_Minimum(Node* root){
// make sure tree is not empty
if(!root)
return -1;
// previous node takes before the last left node
Node* previous = root;
// check left node first for smallest key
if(root->left){
while(root->left){
previous = root;
root = root->left; // 6
} // /
// checks for the case ----> 2
if(!root->right) // \
return previous->data; // 3
}
// Go for minimum successor if exists
if(root->right)
return Successor(root->right);
// checked left and right branch root is on his own
return -1;
}
`
A BST inorder traverse gives elements in order (sorted). So the idea is to return the second element in the traverse(if tree has less than two elements then it won't have second minimum and should return null (not found)).
The following code implements the algorithm. Note that the algorithm can be changed to return the K'th minimum element as well easily.
Code has been written in C# (easily can be written in other languages:-) enjoy!
public static int? FindSecondMimimum(Node node)
{
int current = 0;
return FindKthMinimum(node, 2, ref current);
}
private static int? FindKthMinimum(Node node, int k, ref int current)
{
int? result = null;
if (node == null)
return null;
if (node.Left != null)
{
result = FindKthMinimum(node.Left, k, ref current);
if (result != null)
return result;
}
current++;
if (current == k)
return node.Value;
if (node.Right != null)
{
result = FindKthMinimum(node.Right, k, ref current);
}
return result;
}

AVL Tree. Print element by position (when sorted)

#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct node
{
int key;
struct node *left;
struct node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get height of the tree
int height(struct node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct node* newNode(int key)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct node* insert(struct node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* 2. Update height of this ancestor node */
node->height = max(height(node->left), height(node->right)) + 1;
/* 3. Get the balance factor of this ancestor node to check whether
this node became unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the node with minimum
key value found in that tree. Note that the entire tree does not
need to be searched. */
struct node * minValueNode(struct node* node)
{
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int key)
{
// STEP 1: PERFORM STANDARD BST DELETE
if (root == NULL)
return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if ( key < root->key )
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if( key > root->key )
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if( (root->left == NULL) || (root->right == NULL) )
{
struct node *temp = root->left ? root->left : root->right;
// No child case
if(temp == NULL)
{
temp = root;
root = NULL;
}
else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
}
else
{
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
}
// If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root->height = max(height(root->left), height(root->right)) + 1;
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
// this node became unbalanced)
int balance = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0)
{
root->left = leftRotate(root->left);
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 9);
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 0);
root = insert(root, 6);
root = insert(root, 11);
root = insert(root, -1);
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, 10);
printf("Pre order traversal of the constructed AVL tree is \n");
preOrder(root);
root = deleteNode(root, 10);
printf("\nPre order traversal after deletion of 10 \n");
preOrder(root);
return 0;
}
How can i print an element when I give a certain position?
example:
root = insert(root, 100); (add 100)
root = insert(root, 300); (add 300)
root = insert(root, 200); (add 200)
root = insert(root, 200); (add 400)
PRINT 1 -> Should print the first element (sorted). Which is 100
PRINT 3 -> Should print the third element (sorted). Which is 300
How can I implement this PRINT on my AVL Tree?
I tried to modify this function but i did not succeed
void preOrder(struct node *root)
{
if(root != NULL)
{
preOrder(root->left);
printf("%d ", root->key);
preOrder(root->right);
}
}
I couldn't use a if statment here to check what values are passing because they are all passed at the same time.
preOrder function will order the numbers. lower to biggest.
I don't understand why you can't modify preOrder to do that - you just have to "remember" that current position an update it along the way:
int findPositionPreOrder(
struct node *root,
int targetPos,
int curPos)
{
if(root != NULL)
{
int newPos = findPositionPreOrder(root->left, targetPos, curPos);
newPos++;
if (newPos == targetPos)
{
printf("%d\n", root->key);
}
return findPositionPreOrder(root->right, targetPos, newPos);
}
else
{
return curPos;
}
}
And you call it like findPositionPreOrder(root, targetPosition, 0);
This is not an optimal solution - you can break the recursion after finding your desired position instead of traversing the rest of the tree.

How do you find the nth node in a binary tree?

I want to find the nth node/element in a binary tree. Not the nth largest/smallest, just the nth in inorder order for example.
How would this be done? Is it possible to keep it to one function? Many functions employ an external variable to keep track of the iterations outside of the recursion, but that seems... lazy, for lack of a better term.
You can augment the binary search tree into an order statistic tree, which supports a "return the nth element" operation
Edit: If you just want the ith element of an inorder traversal (instead of the ith smallest element) and don't want to use external variables then you can do something like the following:
class Node {
Node left
Node right
int data
}
class IterationData {
int returnVal
int iterationCount
}
IterationData findNth(Node node, IterationData data, int n) {
if(node.left != null) {
data = findNth(node.left, data, n)
}
if(data.iterationCount < n) {
data.iterationCount++
if(data.iterationCount == n) {
data.returnVal = node.data
return data
} else if(node.right != null) {
return findNth(node.right, data, n)
} else {
return data
}
}
}
You'll need some way to return two values, one for the iteration count and one for the return value once the nth node is found; I've used a class, but if your tree contains integers then you could use an integer array with two elements instead.
In order iterative traversal, keep track of nodes passed in external variable.
public static Node inOrderInterativeGet(Node root, int which){
Stack<Node> stack = new Stack<Node>();
Node current = root;
boolean done = false;
int i = 1;
if(which <= 0){
return null;
}
while(!done){
if(current != null){
stack.push(current);
current = current.getLeft();
}
else{
if(stack.empty()){
done = true;
}
else{
current = stack.pop();
if(i == which){
return current;
}
i++;
current = current.getRight();
}
}
}
return null;
}
One way to do it is to have a size property which is left_subtree + right_subtree + 1:
class Node:
def __init__(self, data=None, left=None, right=None,
size=None):
self.data = data
self.left = left
self.right = right
self.size = size
def select(node, k):
"""Returns node with k-th position in-order traversal."""
if not node:
return None
t = node.left.size if node.left else 0
if t > k:
return select(node.left, k)
elif t < k:
return select(node.right, k - t - 1)
else:
return node
If you don't like global variable, pass to recursive function additional parameter - some int variable, let's call it auto_increment or just ai. ai stores order of current node. Also, recursive function should return maximal value of ai of current vertex subtree,because after visiting whole subtree next 'free' value will be max_ai_in_subreee+1 Something like that
int rec(int vertex,int ai){
traverseOrder[vertex] = ai
if(getChildren(vertex)!=null) return ai;
else{
for(childrens){
ai = rec(child,ai+1);
}
return ai;// subtree visited, return maximal free value upstairs.
}
}
If your function already returns some useful data, it may return some complex object which contains {useful data+ai}
Start from some vertex looks like rec(start_vertex,1);
Below is full code that you can use to find the nth element using inorder in a Binary Tree.
public class NthNodeInInoeder {
static public class Tree {
public int data;
public Tree left,right;
public Tree(int data) {
this.data = data;
}
}
static Tree root;
static int count = 0;
private static void inorder(Tree root2, int num) {
if (root2 == null)
return;
Tree node = root2;
Stack<Tree> stack = new Stack<>();
while (node != null || stack.size() > 0) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
count++;
if (count == num) {
System.out.println(node.data);
break;
}
node = node.right;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
root = new Tree(10);
root.left = new Tree(20);
root.right = new Tree(30);
root.left.left = new Tree(40);
root.left.right = new Tree(50);
int num = sc.nextInt();
inorder(root, num);
sc.close();
}
}

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