Converting a iterative algorithm to recursive - algorithm

I have writing a code to print the tree in Level Order using a queue(Array).
void printLevelOrder(node *root) {
node* queue[10];
node*t=root;
int y=0;
queue[y]=t;
for(int i=0;i<10;i++)
{
printf("%d,",queue[i]->val);
t=queue[i];
if((t->left)!=NULL){
queue[++y]=t->left;
}
if((t->right)!=NULL){
queue[++y]=t->right;
}
}
}
I want to convert the method into a recursive method.
I tried but I am not getting the correct solution. Is it possible to convert this type of problem to using recursive calls?

It is possible to make this recursive, but in this case the result would probably look like the body of the loop in the code above executing and then calling itself for the next element in the queue. It is not possible to convert this into a kind of recursion more often found in tree traversal algorithms, where the recursive method invokes itself for the child nodes of the one it received as an argument. There is thus no performance gain to expect -- you'll still need the queue or some structure like this -- and I don't really see the point in performing the conversion.

I am not sure if this is what you were looking for but it is partial recursion.
void print_level_part(node* p, level) {
if(p) {
if(level==1) {
printf("%d", p->val);
} else {
print_level_part(p->left, level-1);
print_level_part(p->right, level-1);
}
}
}
//the loop in main which does the main printing.
for(int i=0; i<n; ++i) {
print_level_part(root, i);
}
If you want completely recursive solution then I may suggest that you change the for loop in main a recursive function.

This is an example of what Qnan was talking about:
void printNext(node **queue,int i,int y)
{
if (i==y) return;
node *t = queue[i++];
printf("%d,",t->val);
if (t->left) queue[y++] = t->left;
if (t->right) queue[y++] = t->right;
printNext(queue,i,y);
}
void printLevelOrder(node *root)
{
node *queue[10]; /* be careful with hard-coded queue size! */
int y=0, i=0;
queue[y++]=root;
printNext(queue,i,y);
printf("\n");
}

As far as I understand, printing a tree in "Level Order" is actually a BFS traversal of the given tree, for which the recursion is not suited. Recursion is a well-suited approach to DFS.
The recursion internally works with a stack (a LIFO structure), while BFS uses a queue (a FIFO structure). A tree algorithm is suitable for recursion if the solution for a root depends on (the results, or just traversal order) the solutions for the subtrees. Recursion goes to the "bottom" of the tree, and solves the problem from bottom upwards. From this, pre-order, in-order and post-order traversals can be done as recursions:
pre-order : print the root, print the left subtree, print the right subtree
in-order : print the left subtree, print the root, print the right subtree
post-order: print the left subtree, print the right subtree, print the root
Level-order, however, can not be decomposed in "do something for the root, do something for each of the subtrees". The only possible "recursive" implementation would follow #Qnan suggestion, and, as he said, would not make much sense.
What is possible, however, is to transform any recursive algorithm in to an iterative one fairly elegantly. Since the internal recursion actually works with a stack, the only trick in this situation would be to use your own stack instead of the system one. Some of the slight differences between this kind of recursive and iterative implementation would be:
with iterative, you save time on function calls
with recursive, you usually get a more intuitive code
with recursive, extra memory gets allocated for a return address with each function call
with iterative, you allocate the memory, and you determine where the memory is allocated

Related

Non recursive DFS algorithm for simple paths between two points

I am looking for a non-recursive Depth first search algorithm to find all simple paths between two points in undirected graphs (cycles are possible).
I checked many posts, all showed recursive algorithm.
seems no one interested in non-recursive version.
a recursive version is like this;
void dfs(Graph G, int v, int t)
{
path.push(v);
onPath[v] = true;
if (v == t)
{
print(path);
}
else
{
for (int w : G.adj(v))
{
if (!onPath[w])
dfs(G, w, t);
}
}
path.pop();
onPath[v] = false;
}
so, I tried it as (non-recursive), but when i check it, it computed wrong
void dfs(node start,node end)
{
stack m_stack=new stack();
m_stack.push(start);
while(!m_stack.empty)
{
var current= m_stack.pop();
path.push(current);
if (current == end)
{
print(path);
}
else
{
for ( node in adj(current))
{
if (!path.contain(node))
m_stack.push(node);
}
}
path.pop();
}
the test graph is:
(a,b),(b,a),
(b,c),(c,b),
(b,d),(d,b),
(c,f),(f,c),
(d,f),(f,d),
(f,h),(h,f).
it is undirected, that is why there are (a,b) and (b,a).
If the start and end nodes are 'a' and 'h', then there should be two simple paths:
a,b,c,f,h
a,b,d,f,h.
but that algorithm could not find both.
it displayed output as:
a,b,d,f,h,
a,b,d.
stack become at the start of second path, that is the problem.
please point out my mistake when changing it to non-recursive version.
your help will be appreciated!
I think dfs is a pretty complicated algorithm especially in its iterative form. The most important part of the iterative version is the insight, that in the recursive version not only the current node, but also the current neighbour, both are stored on the stack. With this in mind, in C++ the iterative version could look like:
//graph[i][j] stores the j-th neighbour of the node i
void dfs(size_t start, size_t end, const vector<vector<size_t> > &graph)
{
//initialize:
//remember the node (first) and the index of the next neighbour (second)
typedef pair<size_t, size_t> State;
stack<State> to_do_stack;
vector<size_t> path; //remembering the way
vector<bool> visited(graph.size(), false); //caching visited - no need for searching in the path-vector
//start in start!
to_do_stack.push(make_pair(start, 0));
visited[start]=true;
path.push_back(start);
while(!to_do_stack.empty())
{
State &current = to_do_stack.top();//current stays on the stack for the time being...
if (current.first == end || current.second == graph[current.first].size())//goal reached or done with neighbours?
{
if (current.first == end)
print(path);//found a way!
//backtrack:
visited[current.first]=false;//no longer considered visited
path.pop_back();//go a step back
to_do_stack.pop();//no need to explore further neighbours
}
else{//normal case: explore neighbours
size_t next=graph[current.first][current.second];
current.second++;//update the next neighbour in the stack!
if(!visited[next]){
//putting the neighbour on the todo-list
to_do_stack.push(make_pair(next, 0));
visited[next]=true;
path.push_back(next);
}
}
}
}
No warranty it is bug-free, but I hope you get the gist and at least it finds the both paths in your example.
The path computation is all wrong. You pop the last node before you process it's neighbors. Your code should output just the last node.
The simplest fix is to trust the compiler to optimize the recursive solution sufficiently that it won't matter. You can help by not passing large objects between calls and by avoiding allocating/deallocating many objects per call.
The easy fix is to store the entire path in the stack (instead of just the last node).
A harder fix is that you have 2 types of nodes on the stack. Insert and remove. When you reach a insert node x value you add first remove node x then push to the stack insert node y for all neighbours y. When you hit a remove node x you need to pop the last value (x) from the path. This better simulates the dynamics of the recursive solution.
A better fix is to just do breadth-first-search since that's easier to implement in an iterative fashion.

Non-recursive implementation of Flood Fill algorithm?

I'm working on a small drawing application in Java. I'm trying to create a 'bucket-fill' tool by implementing the Flood Fill algorithm.
I tried using a recursion implementation, but it was problematic. Anyway, I searched around the web and it seems that for this purpose, a non-recursive implementation of this algorithm is recommended.
So I ask you:
Could you describe a non-recursive implementation of the Flood Fill algorithm? An actual code example, some pseudo-code, or even a general explanation will all be welcome.
I'm looking for simplest, or the most efficient implementation you can think of.
(Doesn't have to be Java specific).
Thank you
I'm assuming that you have some sort of a grid where you receive the coordinates of the location from where you would like to fill the area.
Recursive flood fill algorithm is DFS. You can do a BFS to convert it to nonrecursive.
Basically the idea is similar in both the algorithms. You have a bag in which the nodes that are yet to be seen are kept. You remove a node from the bag and put the valid neighbors of the node back into the bag.
If the bag is a stack you get a DFS. If it's a queue you get a BFS.
the pseudocode is roughly this.
flood_fill(x,y, check_validity)
//here check_validity is a function that given coordinates of the point tells you whether
//the point should be colored or not
Queue q
q.push((x,y))
while (q is not empty)
(x1,y1) = q.pop()
color(x1,y1)
if (check_validity(x1+1,y1))
q.push(x1+1,y1)
if (check_validity(x1-1,y1))
q.push(x1-1,y1)
if (check_validity(x1,y1+1))
q.push(x1,y1+1)
if (check_validity(x1,y1-1))
q.push(x1,y1-1)
NOTE: make sure that check_validity takes into account whether the point is already colored or not.
DFS: Depth First Search
BFS: Breadth First Search
You basically have two ways to implement a flood fill algorithm non-recursively. The first method has been clearly explained by sukunrt in which you use a queue to implement breadth first search.
Alternatively, you can implement the recursive DFS non-recursively by using an implicit stack. For example, the following code implements a non-recursive DFS on a graph that has nodes as integers. In this code you use an array of Iterator to keep track of the processed neighbors in every node's adjacency list. The complete code can be accessed here.
public NonrecursiveDFS(Graph G, int s) {
marked = new boolean[G.V()];
// to be able to iterate over each adjacency list, keeping track of which
// vertex in each adjacency list needs to be explored next
Iterator<Integer>[] adj = (Iterator<Integer>[]) new Iterator[G.V()];
for (int v = 0; v < G.V(); v++)
adj[v] = G.adj(v).iterator();
// depth-first search using an explicit stack
Stack<Integer> stack = new Stack<Integer>();
marked[s] = true;
stack.push(s);
while (!stack.isEmpty()) {
int v = stack.peek();
if (adj[v].hasNext()) {
int w = adj[v].next();
if (!marked[w]) {
// discovered vertex w for the first time
marked[w] = true;
// edgeTo[v] = w;
stack.push(w);
}
}
else {
// v's adjacency list is exhausted
stack.pop();
}
}
}

Rebalancing an arbitrary BST?

Reference:
I was asked this question #MS SDE interview, 3rd round. And it's not a homework problem. I also gave it a thought and mentioning my approach below.
Question:
Modify a BST so that it becomes as balanced as possible. Needless to mention, you should do it as efficient as possible.
Hint:
Interviewer said that this is a logical question, if you think differently you will get the answer. No difficult coding involved.
--> Having said that, I do not think he was expecting me to point to AVL/RB Trees.
My Solution:
I proposed that, I would do inorder traversal of tree, take middle element as root of new tree(lets call it new root). Then go to the left part of middle element, take its middle element as root of left subtree of tree rooted new root. Similarly do for right part.
Doing this recursively will give the optimal balanced BST.
Why I am posting it here:
But he was not satisfied with the answer :( So, is there really a way of doing this w/o going for weights/RB coloring strategy, or was he just fooling around with me?
Please put in your expert thoughts.
Duplicate? No!
I know there is this question but the solution proposed by requester is too complicated, and other one talks about AVL trees.
You might want to look into the Day-Stout-Warren algorithm, which is an O(n)-time, O(1)-space algorithm for reshaping an arbitrary binary search tree into a complete binary tree. Intuitively, the algorithm works as follows:
Using tree rotations, convert the tree into a degenerate linked list.
By applying selective rotations to the linked list, convert the list back into a completely balanced tree.
The beauty of this algorithm is that it runs in linear time and requires only constant memory overhead; in fact, it just reshapes the underlying tree, rather than creating a new tree and copying over the old data. It is also relatively simple to code up.
Hope this helps!
"Balanced as possible" = complete (or full) binary tree1. You cannot get more balanced that it.
The solution is simple - build an "empty" complete binary tree, and iterate the new tree and the input tree (simultaneously) in inorder-traversal to fill the complete tree.
When you are done, you have the most balanced tree you can get, and time complexity of this approach is O(n).
EDIT:
This should be done following these steps:
Build a dummy complete tree with n nodes. All the values to each
node will be initialized to some garbage value.
Create two iterators: (1) originalIter for the original tree, (2) newIter for the new (initialized with garbage) tree. Both iterators will return elements in in-order traversal.
Do the following to fill the tree with the values from the original:
while (originalIter.hasNext()):
newIter.next().value = originalIter.next().value
(1) (From Wikipedia): A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible
The DSW algorithm can solve this is O(n) time. The algorithm goes as follows:
1] Using right-rotation operations, turn the tree into a linked list
(a.k.a. backbone or vine)
2] Rotate every second node of the backbone about its parent to turn
the backbone into a perfectly balanced BST.
Reference
This will convert your normal BST into a balanced BST with minimum possible height in O(n). First, save all your nodes sorted into a vector. Then, the root is the mid element and recursively build a tree from 0 to mid-1 as its left and build a tree from mid+1 to vector.size()-1 as its right child. After all these steps root keeps the balanced BST with the min-height.
import java.util.Vector;
public class ConvertBSTIntoBalanced {
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
node1.right = node2;
node2.right = node3;
node3.right = node4;
ConvertBSTIntoBalanced convertBSTIntoBalanced = new ConvertBSTIntoBalanced();
TreeNode balancedBSTRoot = convertBSTIntoBalanced.balanceBST(node1);
}
private void saveNodes(TreeNode node, Vector<TreeNode> nodes) {
if (node == null)
return;
saveNodes(node.left, nodes);
nodes.add(node);
saveNodes(node.right, nodes);
}
private TreeNode buildTree(Vector<TreeNode> nodes, int start, int end) {
if (start > end)
return null;
int mid = (start + end) / 2;
TreeNode midNode = nodes.get(mid);
midNode.left = buildTree(nodes, start, mid - 1);
midNode.right = buildTree(nodes, mid + 1, end);
return midNode;
}
public TreeNode balanceBST(TreeNode root) {
Vector<TreeNode> nodes = new Vector<>();
saveNodes(root, nodes);
return buildTree(nodes, 0, nodes.size() - 1);
}
public class TreeNode {
public Integer val;
public TreeNode left;
public TreeNode right;
public TreeNode(Integer x) {
val = x;
}
}
}
I hope it helps.

Implementing recursion without a separate function

I was wondering how (or maybe even if it's possible) to implement recursion without a separate function that calls itself.
So far all algorithms implementing recursion I've seen use a separate function. I thought a lot and came up with the idea that a goto statement with some variable mutation can do the job but I'm really unsure about that.
I made a mini research and found info about this Structured programming theorem which proves that every algorithm can be implemented with only three data structures, so such a recursion implementation must be posible but I still cannot assemble everything into consistent knowledge and understanding for the whole would-be approach.
What you are looking for is basically expressing a recursive function into an iterative form.
This can easily be done by using a Stack. Here's a very simple example in C#:
int NodeCount(Node n)
{
if (n.Visited) return 0; // This node was visited through another node, discard
n.Visited = true;
int res = 1;
foreach (Node ni in n.Children) // Recurse on each node
{
res += NodeCount(ni); // Add the number of sub node for each node
}
return res;
}
Here's the exact same function in iterative form:
int NodeCount(Node root)
{
int res = 0;
Stack<int> stk = new Stack<int>();
stk.Push(root) // We start with the root node
while( stk.Count > 0) // While we still have nodes to visit
{
Node current = stk.Pop(); // Get the node on top of the stack
current.Visited = true; // Mark it as visited
res ++; // Add one to the count
foreach (Node ni in n.Children) // Push all non visited children to the stack
{
if (ni.Visited == false)
stk.Push(ni);
}
}
return res;
}
to implement recursion without a separate function that calls itself.
Yes it is possible to convert a recursive algorithm to an iterative one. But why would you want to use a goto statement? When you make a function call the assembly generated has a branch instruction to jumb to the specific function which acts similar to a goto.
So what you would accomplish is somewhat similar to what the machine code would eventually do, with the benefit of avoiding stack frame calls and the disadvantage of the horrible spaggeti code from using goto.
If you want to avoid recursion, use iteration. How did you come up with this question?
You can perform a sort of a recursion without a function using any stack-based language. For example, in Forth you can write the fibonacci function like this:
: fibonacci 0 1 10 0 do 2dup + rot . loop swap . . ;
This program recursively generates 10 iterations of the fibonacci sequence, each iteration using the inputs from the previous iteration. No function is called.

How to print a binary tree level by level? Interview question!

How to print a binary tree level by level?
This is an interview question I got today. Sure enough, using a BFS style would definitely work. However, the follow up question is: How to print the tree using constant memory? (So no queue can be used)
I thought of converting the binary tree into a linked list somehow but have not come up with a concrete solution.
Any suggestions?
Thanks
One way to avoid using extra memory (much extra, anyway) is to manipulate the tree as you traverse it -- as you traverse downward through nodes, you make a copy of its pointer to one of the children, then reverse that to point back to the parent. When you've gotten to the bottom, you follow the links back up to the parents, and as you go you reverse them to point back to the children.
Of course, that's not the whole job, but it's probably the single "trickiest" part.
Extending on what Jerry Coffin said, I had asked a question earlier about doing something similar using in-order traversal. It uses the same logic as explained by him.
Check it out here:
Explain Morris inorder tree traversal without using stacks or recursion
You can do it by repeatedly doing an in-order traversal of the tree while printing only those nodes at the specified level. However, this isn't strictly constant memory since recursion uses the call stack. And it's super inefficient. Like O(n * 2^n) or something.
printLevel = 1;
while(moreLevels) {
moreLevels = printLevel(root, 1, printLevel);
printLevel++;
}
boolean printLevel(Node node, int currentLevel, int printLevel) {
boolean moreLevels = false;
if(node == null) {
return(false);
}
else if(currentLevel == printLevel) {
print the node value;
}
else {
moreLevels |= printLevel(node.leftChild, currentLevel + 1, printLevel);
moreLevels |= printLevel(node.rightChild, currentLevel + 1, printLevel);
}
return(moreLevels);
}

Resources