print all paths from root to leaves n-ary tree - algorithm

I am trying to print all paths from root to all leaves in n-ary tree. This code prints the paths to the leaves, but it also prints subpaths too.
For example, let's say one path is 1-5-7-11. It prints 1-5-7-11, but it also prints 1-5-7, 1-5, so on.
How can I avoid this printing subpaths ?
Here is my code in matlab
Thanks
stack=java.util.Stack();
stack.push(0);
CP = [];
Q = [];
labels = ones(1,size(output.vertices,2));
while ~stack.empty()
x = stack.peek();
for e = 1:size(output.edges,2)
if output.edges{e}(1) == x && labels(output.edges{e}(2)+1) == 1
w = output.edges{e}(2);
stack.push(w);
CP = union(CP,w);
break
end
end
if e == size(output.edges,2)
Q = [];
for v=1:size(CP,2)
Q = union(Q,CP(v));
end
disp(Q)
stack.pop();
labels(x+1) = 0;
CP = CP(find(CP~=x));
end
end

Let's split the problem in two parts.
1. Find all leaf-nodes in a tree
input: Tree (T), with nodes N
output: subset of N (L), such that each node in L is a leaf
initialize an empty stack
push the root node on the stack
while the stack is not empty
do
pop a node from the stack, call it M
if M is a leaf, add it to L
if M is not a leaf, push all its children on the stack
done
2. Given a leaf, find its path to the root
input: leaf node L
output: a path from L to R, with R being the root of the tree
initialize an empty list (P)
while L is not the root of the tree
do
append L to the list
L = parent of L
done
return P

Related

Find algorithm : Reconstruct a sequence with the minimum length combination of disjointed subsequences chosen from a list of subsequences

I do not know if it’s appropriate to ask this question here so sorry if it is not.
I got a sequence ALPHA, for example :
A B D Z A B X
I got a list of subsequences of ALPHA, for example :
A B D
B D
A B
D Z
A
B
D
Z
X
I search an algorithm that find the minimum length of disjointed subsequences that reconstruct ALPHA, for example in our case :
{A B D} {Z} {A B} {X}
Any ideas? My guess is something already exists.
You can transform this problem into finding a minimum path in a graph.
The nodes will correspond to prefixes of the string, including one for the empty string. There will be an edge from a node A to a node B if there is an allowed sub-sequence that, when appended to the string prefix A, the result is the string prefix B.
The question is now transformed into finding the minimum path in the graph starting from the node corresponding to the empty string, and ending in the node corresponding to the entire input string.
You can now apply e.g. BFS (since the edges have uniform costs), or Dijkstra's algorithm to find this path.
The following python code is an implementation based on the principles above:
def reconstruct(seq, subseqs):
n = len(seq)
d = dict()
for subseq in subseqs:
d[subseq] = True
# in this solution, the node with value v will correspond
# to the substring seq[0: v]. Thus node 0 corresponds to the empty string
# and node n corresponds to the entire string
# this will keep track of the predecessor for each node
predecessors = [-1] * (n + 1)
reached = [False] * (n + 1)
reached[0] = True
# initialize the queue and add the first node
# (the node corresponding to the empty string)
q = []
qstart = 0
q.append(0)
while True:
# test if we already found a solution
if reached[n]:
break
# test if the queue is empty
if qstart > len(q):
break
# poll the first value from the queue
v = q[qstart]
qstart += 1
# try appending a subsequence to the current node
for n2 in range (1, n - v + 1):
# the destination node was already added into the queue
if reached[v + n2]:
continue
if seq[v: (v + n2)] in d:
q.append(v + n2)
predecessors[v + n2] = v
reached[v + n2] = True
if not reached[n]:
return []
# reconstruct the path, starting from the last node
pos = n
solution = []
while pos > 0:
solution.append(seq[predecessors[pos]: pos])
pos = predecessors[pos]
solution.reverse()
return solution
print reconstruct("ABDZABX", ["ABD", "BD", "AB", "DZ", "A", "B", "D", "Z", "X"])
I don't have much experience with python, that's the main reason why I preferred to stick to the basics (e.g. implementing a queue with a list + an index to the start).

Print all root to leaf paths with there relative positions

Given a binary tree, how do we print the root to the leaf path, but add “_” to indicate the relative position?
Example:
Input : Root of below tree
A
/ \
B C
/ \ / \
D E F G
Output : All root to leaf paths
_ _ A
_ B
D
_ A
B
_ E
A
_ C
F
A
_ C
_ _ G
You can use preorder travel to visit the tree. Record the path with the indent.
When visit left child decrease the indent, when visit right child increase the indent. Then you are able to get the path like,
(0, A), (-1, B), (-2, D)
(0, A), (-1, B), (0, E)
...
During the output phase, normalize the path, find the smallest indent for the path node and shift the path nodes to,
(2, A), (1, B), (0, D)
(1, A), (0, B), (1, E)
...
And then print the path accordingly.
Here's the sample code in python,
def travel(node, indent, path):
if not node:
print_path(path)
return
path.append((indent, node))
if node.left:
travel(node.left, indent - 1, path)
if node.right:
travel(node.right, indent + 1, path)
del path[-1]
def print_path(path):
min_indent = abs(min([x[0] for x in path]))
for indent, node in path:
p = []
for x in xrange(min_indent + indent):
p.append('_')
p.append(node.val)
print ' '.join(p)
The idea base on print path in vertical order.
1) We do Preorder traversal of the given Binary Tree. While traversing the tree, we can recursively calculate horizontal distances or HDs. We initially pass the horizontal distance as 0 for root. For left subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1. For every HD value, we maintain a list of nodes in a vector (” that will store information of current node horizontal distance and key value of root “).we also maintain the order of node (order in which they appear in path from root to leaf). for maintaining the order.
2) While we reach to leaf node during traverse we print that path with underscore "_"
a) First find the minimum Horizontal distance of the current path.
b) After that we traverse current path
First Print number of underscore “_” : abs (current_node_HD – minimum-HD)
Print current node value.
Do this process for all root to leaf path.
I could not get Qiang Jin's response to work quite right. Switched a few things around.
class Node:
def __init__(self, val):
self.value = val
self.right = None
self.left = None
def printTreeRelativePaths(root):
indent = 0
path = []
preOrder(root, indent, path)
def preOrder(node, indent, path):
path.append((node, indent))
if not node.left and not node.right:
processPath(path)
if node.left:
preOrder(node.left, indent - 1, path)
if node.right:
preOrder(node.right, indent + 1, path)
del path[-1]
def processPath(path):
minIndent = 0
for element in path:
if element[1] < minIndent:
minIndent = element[1]
offset = abs(minIndent)
for element in path:
print ('_' * (offset + element[1])) + element[0].value
root = Node('A')
root.left = Node('B')
root.right = Node('C')
root.left.left = Node('D')
root.left.right = Node('E')
root.right.left = Node('F')
root.right.right = Node('G')
printTreeRelativePaths(root)

Removing edge that causes a cycle in an undirected graph

I have a graph that is represented by an adjacency matrix, G and I am trying to use DFS to remove an edge that causes a cycle
There can be multiple cycles, but I figure it is probably best to remove them one at a time, so I only need my algorithm to find one cycle, and that can be repeated.
Here is the code for what I have got so far:
function [ G, c_flag, c_stack, o_stack, cptr, optr ] =...
dfs_cycle( G, curr_v, c_stack, o_stack, cptr, optr, c_flag )
% add current vertex to open list
optr = optr + 1;
o_stack(optr) = curr_v;
% find adjacent vertices
adj_v = find(G(curr_v,:));
for next_v = adj_v
% ensure next_v is not in closed list
if ~any(c_stack == next_v)
% if next_v in open list then cycle exists
if any(o_stack == next_v)
% remove edge and set flag to 1
G(curr_v, next_v) = 0;
G(next_v, curr_v) = 0;
c_flag = 1;
break;
end
[G, c_flag, c_stack, o_stack, cptr, optr] =...
dfs_cycle(G, next_v, c_stack, o_stack, cptr, optr, c_flag);
if c_flag == 1
break;
end
% remove vertex from open list and put into closed list
o_stack(optr) = 0;
optr = optr - 1;
cptr = cptr + 1;
c_stack(cptr) = next_v;
end
end
end
the function is called using:
v_list = find(sum(G)>0);
o_stack = zeros(1,numel(v_list));
c_stack = o_stack;
optr = 0;
cptr = 0;
root_v = v_list(randperm(length(v_list),1));
c_flag = 0;
[G_dash,c_flag,~,~,~,~] =...
dfs_cycle(G, root_v, c_stack, o_stack, cptr, optr, c_flag);
It should return the modified (if cycle found) adjacency matrix, G_dash and c_flag corresponding to whether a cycle was found or not.
However, it doesnt seem to be functioning as it should.
I think I have located the problem; in the line if any(o_stack == next_v) it will return true, because the previous vertex visited is usually still in o_stack, however I am not sure how I should go about fixing this.
Does anyone have any ideas?
A connected, un-directed, acyclic graph is called a tree, with n nodes and n - 1 edges. For a formal proof, see here.
So, to form a tree from your graph, you just need to run DFS once, and keep all edges used by this DFS (for more information about tree created by DFS, see wiki link, example section). Those unused edges can be removed.

How to keep track of depth in breadth first search?

I have a tree as input to the breadth first search and I want to know as the algorithm progresses at which level it is?
# Breadth First Search Implementation
graph = {
'A':['B','C','D'],
'B':['A'],
'C':['A','E','F'],
'D':['A','G','H'],
'E':['C'],
'F':['C'],
'G':['D'],
'H':['D']
}
def breadth_first_search(graph,source):
"""
This function is the Implementation of the breadth_first_search program
"""
# Mark each node as not visited
mark = {}
for item in graph.keys():
mark[item] = 0
queue, output = [],[]
# Initialize an empty queue with the source node and mark it as explored
queue.append(source)
mark[source] = 1
output.append(source)
# while queue is not empty
while queue:
# remove the first element of the queue and call it vertex
vertex = queue[0]
queue.pop(0)
# for each edge from the vertex do the following
for vrtx in graph[vertex]:
# If the vertex is unexplored
if mark[vrtx] == 0:
queue.append(vrtx) # mark it as explored
mark[vrtx] = 1 # and append it to the queue
output.append(vrtx) # fill the output vector
return output
print breadth_first_search(graph, 'A')
It takes tree as an input graph, what I want is, that at each iteration it should print out the current level which is being processed.
Actually, we don't need an extra queue to store the info on the current depth, nor do we need to add null to tell whether it's the end of current level. We just need to know how many nodes the current level contains, then we can deal with all the nodes in the same level, and increase the level by 1 after we are done processing all the nodes on the current level.
int level = 0;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int level_size = queue.size();
while (level_size-- != 0) {
Node temp = queue.poll();
if (temp.right != null) queue.add(temp.right);
if (temp.left != null) queue.add(temp.left);
}
level++;
}
You don't need to use extra queue or do any complicated calculation to achieve what you want to do. This idea is very simple.
This does not use any extra space other than queue used for BFS.
The idea I am going to use is to add null at the end of each level. So the number of nulls you encountered +1 is the depth you are at. (of course after termination it is just level).
int level = 0;
Queue <Node> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
while(!queue.isEmpty()){
Node temp = queue.poll();
if(temp == null){
level++;
queue.add(null);
if(queue.peek() == null) break;// You are encountering two consecutive `nulls` means, you visited all the nodes.
else continue;
}
if(temp.right != null)
queue.add(temp.right);
if(temp.left != null)
queue.add(temp.left);
}
Maintain a queue storing the depth of the corresponding node in BFS queue. Sample code for your information:
queue bfsQueue, depthQueue;
bfsQueue.push(firstNode);
depthQueue.push(0);
while (!bfsQueue.empty()) {
f = bfsQueue.front();
depth = depthQueue.front();
bfsQueue.pop(), depthQueue.pop();
for (every node adjacent to f) {
bfsQueue.push(node), depthQueue.push(depth+1);
}
}
This method is simple and naive, for O(1) extra space you may need the answer post by #stolen_leaves.
Try having a look at this post. It keeps track of the depth using the variable currentDepth
https://stackoverflow.com/a/16923440/3114945
For your implementation, keep track of the left most node and a variable for the depth. Whenever the left most node is popped from the queue, you know you hit a new level and you increment the depth.
So, your root is the leftMostNode at level 0. Then the left most child is the leftMostNode. As soon as you hit it, it becomes level 1. The left most child of this node is the next leftMostNode and so on.
With this Python code you can maintain the depth of each node from the root by increasing the depth only after you encounter a node of new depth in the queue.
queue = deque()
marked = set()
marked.add(root)
queue.append((root,0))
depth = 0
while queue:
r,d = queue.popleft()
if d > depth: # increase depth only when you encounter the first node in the next depth
depth += 1
for node in edges[r]:
if node not in marked:
marked.add(node)
queue.append((node,depth+1))
If your tree is perfectly ballanced (i.e. each node has the same number of children) there's actually a simple, elegant solution here with O(1) time complexity and O(1) space complexity. The main usecase where I find this helpful is in traversing a binary tree, though it's trivially adaptable to other tree sizes.
The key thing to realize here is that each level of a binary tree contains exactly double the quantity of nodes compared to the previous level. This allows us to calculate the total number of nodes in any tree given the tree's depth. For instance, consider the following tree:
This tree has a depth of 3 and 7 total nodes. We don't need to count the number of nodes to figure this out though. We can compute this in O(1) time with the formaula: 2^d - 1 = N, where d is the depth and N is the total number of nodes. (In a ternary tree this is 3^d - 1 = N, and in a tree where each node has K children this is K^d - 1 = N). So in this case, 2^3 - 1 = 7.
To keep track of depth while conducting a breadth first search, we simply need to reverse this calculation. Whereas the above formula allows us to solve for N given d, we actually want to solve for d given N. For instance, say we're evaluating the 5th node. To figure out what depth the 5th node is on, we take the following equation: 2^d - 1 = 5, and then simply solve for d, which is basic algebra:
If d turns out to be anything other than a whole number, just round up (the last node in a row is always a whole number). With that all in mind, I propose the following algorithm to identify the depth of any given node in a binary tree during breadth first traversal:
Let the variable visited equal 0.
Each time a node is visited, increment visited by 1.
Each time visited is incremented, calculate the node's depth as depth = round_up(log2(visited + 1))
You can also use a hash table to map each node to its depth level, though this does increase the space complexity to O(n). Here's a PHP implementation of this algorithm:
<?php
$tree = [
['A', [1,2]],
['B', [3,4]],
['C', [5,6]],
['D', [7,8]],
['E', [9,10]],
['F', [11,12]],
['G', [13,14]],
['H', []],
['I', []],
['J', []],
['K', []],
['L', []],
['M', []],
['N', []],
['O', []],
];
function bfs($tree) {
$queue = new SplQueue();
$queue->enqueue($tree[0]);
$visited = 0;
$depth = 0;
$result = [];
while ($queue->count()) {
$visited++;
$node = $queue->dequeue();
$depth = ceil(log($visited+1, 2));
$result[$depth][] = $node[0];
if (!empty($node[1])) {
foreach ($node[1] as $child) {
$queue->enqueue($tree[$child]);
}
}
}
print_r($result);
}
bfs($tree);
Which prints:
Array
(
[1] => Array
(
[0] => A
)
[2] => Array
(
[0] => B
[1] => C
)
[3] => Array
(
[0] => D
[1] => E
[2] => F
[3] => G
)
[4] => Array
(
[0] => H
[1] => I
[2] => J
[3] => K
[4] => L
[5] => M
[6] => N
[7] => O
)
)
Set a variable cnt and initialize it to the size of the queue cnt=queue.size(), Now decrement cnt each time you do a pop. When cnt gets to 0, increase the depth of your BFS and then set cnt=queue.size() again.
In Java it would be something like this.
The idea is to look at the parent to decide the depth.
//Maintain depth for every node based on its parent's depth
Map<Character,Integer> depthMap=new HashMap<>();
queue.add('A');
depthMap.add('A',0); //this is where you start your search
while(!queue.isEmpty())
{
Character parent=queue.remove();
List<Character> children=adjList.get(parent);
for(Character child :children)
{
if (child.isVisited() == false) {
child.visit(parent);
depthMap.add(child,depthMap.get(parent)+1);//parent's depth + 1
}
}
}
Use a dictionary to keep track of the level (distance from start) of each node when exploring the graph.
Example in Python:
from collections import deque
def bfs(graph, start):
queue = deque([start])
levels = {start: 0}
while queue:
vertex = queue.popleft()
for neighbour in graph[vertex]:
if neighbour in levels:
continue
queue.append(neighbour)
levels[neighbour] = levels[vertex] + 1
return levels
I write a simple and easy to read code in python.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, root):
assert root is not None
queue = [root]
level = 0
while queue:
print(level, [n.val for n in queue if n is not None])
mark = len(queue)
for i in range(mark):
n = queue[i]
if n.left is not None:
queue.append(n.left)
if n.right is not None:
queue.append(n.right)
queue = queue[mark:]
level += 1
Usage,
# [3,9,20,null,null,15,7]
n3 = TreeNode(3)
n9 = TreeNode(9)
n20 = TreeNode(20)
n15 = TreeNode(15)
n7 = TreeNode(7)
n3.left = n9
n3.right = n20
n20.left = n15
n20.right = n7
DFS().dfs(n3)
Result
0 [3]
1 [9, 20]
2 [15, 7]
I don't see this method posted so far, so here's a simple one:
You can "attach" the level to the node. For e.g., in case of a tree, instead of the typical queue<TreeNode*>, use a queue<pair<TreeNode*,int>> and then push the pairs of {node,level}s into it. The root would be pushed in as, q.push({root,0}), its children as q.push({root->left,1}), q.push({root->right,1}) and so on...
We don't need to modify the input, append nulls or even (asymptotically speaking) use any extra space just to track the levels.

left rotation in bst with 4 fields

I have some problem with this and I tried a lot to solve it. I understand how rotation of bst work but I could not conform it to this structure.
Assume that the object Node of the binary search tree (BST) is described by 4 fields : key (integer), leftChild, rightChild and parent all are references to a Node of the BST.
Write the code of leftRotation (Node p).
this is my trying code:
Node temp
temp = parent.right// could I do like this ??
parent.rightChild = temp.leftChild
temp.leftChild= parent
i feel it is totally wrong because I just wanna work with only those four fields.
I just want a pseudo code.
thank you for help!
regards
Assuming you don't know is p left child or right child of it's parent
q = p.right
if p.parent <> nil then
if p.parent.right = p then
p.parent.right = q
else
p.parent.left = q
q.parent = p.parent
q.left.parent = p
p.right = q.left
q.left = p
p.parent = q

Resources