Find the longest path between any two nodes - java

I have a binary tree. I need to write Java recursive method that will give longest path between two nodes.
For example longest path if following tree is 7 (7-8-5-13-15-18-16-17).
http://img294.imageshack.us/img294/130/treeb.jpg
What's the way to resolve this problem?
(The method: public static int longestPath(Node n) )

Considering this is homework I'd look at Depth-First search and Breadth-First search.
With a preference for depth-first

To start with, you can write a function that returns the height of the tree, which is equal to the length of the longest path.

Here is a clue:
First, can you solve this simpler problem?
Find the max from a list of integers.
Second, a new path occurs whenever a node has children.

Also note that the problem is NP-complete, so you probably won't be able to find a polynomial algorithm.

Related

How to Implement Binary Search Trees (Within the parameters of my questions)?

I am struggling in a data structures course where my professor is either absent or not answering. I have an assignment due within a day or so and have no clue where to even start in terms of answering them. If somebody could explain what to do and how it'd be much appreciated. Also, I'm somewhat new to StackOverflow, if I misformatted my question or did something wrong please let me know before a downvote, I would just like some help, thanks.
Write the definition of the method nodeCount that returns the number of nodes in a binary tree. Add this method to the class BinaryTree and create a program (the main class with the main method) to test this method. (Note: To test your algorithm, first create a binary search tree).
Write a method, swapSubtrees, that swaps all of the left and right subtrees of a binary tree. Add this method to the class BinaryTree and create a program (the main class with the main method) to test this method. (Note: To test your algorithm, first create a binary search tree).
You can find a tutorial on how to implement a binary tree in java here.
To count the nodes in a tree you should try to use a recursive method that count's and summs up the size of the sub-trees. In pseudocode:
int count(TreeNode node):
if (node.hasNoMoreSubNodes):
return 1
else:
sum = count(node.left) + count(node.right) + 1
return sum
I'm not quite shure what's the point in the second question. You could do something like this (pseudocode):
void swapSubTrees(TreeNode node):
TreeNode tmp = node.left
node.left = node.right
node.right = tmp
This would swap the subtrees of the binary-tree, but after this the structure you have is no longer a binary-search-tree, but only a binary-tree. So this operation would be quite useless if it's executed on a binary-search-tree...
Hope this helps.

(Algorithm) find nodes having single path to reach from one node to other

I wanted to know fastest algorithm for finding nodes have only path from one node to other nodes.
these nodes are represented in string like this:
String path = "({A,B,C,D,E,F},{(A,C),(B,C),(C,E),(B,E),(B,D),(E,F)})";
Output should be like this:
output = {(A,C),(B,D),(E,F)}
I tried split() method but its an long procedure I would greatly appreciate any help you can give me in working this problem
It seems to me that you need to:
Find the cycles in your graph
Eliminate all edges that contribute to a cycle

How to implement Greedy Search algorithm

I have a project that is given on my Artificial Intelligence course. I need to implement Greedy Search algorithm for my program. Description of my project is:
Two text files called “tree.txt” and “heuristic.txt” are given. “tree.txt” will define the search tree where each line will contain a parent-child relation and a path cost between them. Each data will be seperated with a space.
e.g.
A B 5
A C 3
B D 6
The first character in the first line will be the Start node (A in here) and the goal node will be “G”.
“heuristic.txt” will define the heuristic, h(n), values. Each line will contain the heuristic value of each node. Each data will be seperated with a space.
e.g.
A 20
B 15
C 18
Output:
The program should give the solution path and the path cost from start node to goal.
Now my problem is that i am familiar with Greedy Search theoretically, but never implemented it practically in coding. I really dont know from where to start. We are free to develop our program in any language. Mostly, i have skills in Java and C#. If anybody can give me some ideas, or help me with any similar examples or tutorials. Any kind of help will be greatly appreciated. Sorry for so much writing. Thank you in advance:)))
I suggest this solution using python.
To implement the graph in your program use a simple python dictionary. Here's the code:
class Tree:
def _init_(self,dict,heuristic):
self.tree=tree
self.heuristic=heuristic
def getHeuristicValue(self,state)
value=self.heuristic.get(state)
return value
The constructor call is something like:
g = Graph({'A':{'B':5,'C':3},'B':{'D':6}},{'A':20,'B':15,'C':18})
The getHeuristic python function pass accepts a state as an argument and returns the value of the heuristic of this state.
To learn about python's dictionary class I suggest you read the tutorial
To implement the search algorithm with python you should implement this simple pseudocode:
function Tree-Search(initialNode,goalNode) returns a solution,or failure
frontier.push(initialNode) with the value of the function heuristic(initialNode.state)+the path cost to reaxh this node
while(frontier)
node<-frontier.pop()
if node.state==GoalNode.state
return node
expand node, adding the resulting nodes to the frontier
return None
For the frontier you must use a priority queue because you must pop the node with the lower value of g(n)+h(n) (where g(n) is the path cost to reach this node and h(n) is the value of the heuristic function).
To implement priority queue you should use a heap of the standard library heapq
The node is a data structure that must contain four components:
node.state:the state in the state space to which the node corresponds.
node.parent:the node in the search tree that generated this node.
node.action: the action that was applied to the parent to generated the node.
node.pathCost: is g(n),the cost of the path from the initial state to the node.
Lastly, for expanding the node, you can use this python function:
def actions(self,state):
'''return a tuple that contain the state child of state '''
return tuple(self.tree.get(state))
I suggest you to look this for your problem.
You can get the solution simply go back from the node.state that returns from the output of the algorithm while node.parent is not null that is your solution.
I hope this is useful for your project.

A* search algorithm determine loop variable when no path exists

I´ m trying to implement the A* search algorithm in Java, and I have a question:
How many times I need to run a A* loop, until there is clearly no existing path?
For Example: If i have a for-loop; how long should "i" increase?
When you have explored all nodes that you can reach with A*, without finding your goal, then you can assume that there is no path.
I think you are thinking of A* the wrong way.
You run it until there are no more nodes to search. If you havent reached your target by then there is no path.
Psuedo:
//Our list of still open nodes
List<Node> nodesToSearch = new List<Node>();
while (nodesToSearch.Count > 0)
{
//SearchNode, if its our target we are done
//Add reachable neighbours to the list of nodes to search. So next iteration we will continue on searching those
//Remove current node.. since its searched
}
//If we end up here without a target there is no path.
//That means we have searched all nodes and their neighbours etc etc etc. Without reaching the target.

Java Algorithm for finding the largest set of independent nodes in a binary tree

By independent nodes, I mean that the returned set can not contain nodes that are in immediate relations, parent and child cannot both be included. I tried to use Google, with no success. I don't think I have the right search words.
A link, any help would be very much appreciated. Just started on this now.
I need to return the actual set of independent nodes, not just the amount.
You can compute this recursive function with dynamic programming (memoization):
MaxSet(node) = 1 if "node" is a leaf
MaxSet(node) = Max(1 + Sum{ i=0..3: MaxSet(node.Grandchildren[i]) },
Sum{ i=0..1: MaxSet(node.Children[i]) })
The idea is, you can pick a node or choose not to pick it. If you pick it, you can't pick its direct children but you can pick the maximum set from its grandchildren. If you don't pick it, you can pick maximum set from the direct children.
If you need the set itself, you just have to store how you selected "Max" for each node. It's similar to the LCS algorithm.
This algorithm is O(n). It works on trees in general, not just binary trees.
I would take-and-remove all leaves first while marking their parents as not-to-take, then remove all leaves that are marked until no such leaves are left, then recurse until the tree is empty. I don't have a proof that this always produces the largest possible set, but I believe it should.
I've provided an answer to a question for the same problem, although the solution is in python, the explanation, algorithm, and test cases could be applicable.

Categories