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.
Related
I've been going through algorithm challenges on LeetCode and just completed "Remove Nth Node From End of List".
Many of the top answers claimed to have found a "one pass" solution and I've included a Java example below.
Please could someone explain why "while(n-->0) h2=h2.next;" doesn't count as an extra pass of the linked list and, therefore, make this a "two pass" solution?
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode h1=head, h2=head;
while(n-->0) h2=h2.next;
if(h2==null)return head.next; // The head need to be removed, do it.
h2=h2.next;
while(h2!=null){
h1=h1.next;
h2=h2.next;
}
h1.next=h1.next.next; // the one after the h1 need to be removed
return head;
}
I've looked in the comments to this and other solutions and couldn't find an answer. Equally, a general Google search didn't yield an explanation.
Thanks in advance.
No, it's not one-pass. One-pass is defined with respect to a sequential I/O mechanism (canonically a tape) and means that each piece of data is read at most once, in order. Analogizing the linked list to the tape here, this algorithm is not one-pass because in general, some node will have its next field read once by h2=h2.next (in either loop) and again by h1=h1.next in the second loop.
The algorithm is not single pass, but not because of the first loop.
The first loop performs a partial pass on n elements.
The second loop performs two simultaneous partial passes on l-n elements (that on h2 being complementary to that in the first loop). In total, 2l-n lookups of next fields.
A single-pass solution can be implemented with the help of a FIFO queue of length n, but this is "hiding" a partial pass.
I'm studying Trees in Java, and came across some confusing lines in the book I'm studying. The diagram given for the in-order traversal is this:
The code for the traversal (recursive) is:
private void inOrder(Node leftRoot) {
if (localRoot != null) {
inOrder(localRoot.leftChild);
System.out.println(localRoot.iData + " ");
inOrder(localRoot.rightChild);
}
}
The lines I'm confused at are:
Now we’re back to inOrder(A), just returning from traversing A’s left
child. We visit A and then call inOrder() again with C as an argument,
creating inOrder(C). Like inOrder(B), inOrder(C) has no children, so
step 1 returns with no action, step 2 visits C, and step 3 returns
with no action. inOrder(B) now returns to inOrder(A).
However,
inOrder(A) is now done, so it returns and the entire traversal is
complete. The order in which the nodes were visited is A, B, C; they
have been visited inorder. In a binary search tree this would be the
order of ascending keys.
I've highlighted the parts where I'm stuck at. First, I think in the third step, inOrder(C)[and not inOrder(B)] returns to inOrder(A).And second, the order in which the nodes were visited should be B -> A -> C.
Please help me out!
Yes, you are correct on both counts. These seem to be typos, or errata.
As a sidenote, I recognized the diagram style in your post because I learned data structures years ago from the same book (Lafore). Unfortunately it does not seem that he has a list of errata published anywhere, which is disappointing, since most authors do strive to do this.
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.
I am using a Breadth first search in a program that is trying to find and return the shortest path between two nodes on an unweighted digraph.
My program works like the wikipedia page psuedo code
The algorithm uses a queue data structure to store intermediate results as it traverses the graph, as follows:
Enqueue the root node
Dequeue a node and examine it
If the element sought is found in this node, quit the search and return a result.
Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
If the queue is not empty, repeat from Step 2.
So I have been thinking of how to track number of steps made but I am having trouble with the limitations of java (I am not very knowledgeable of how java works). I originally was thinking that I could create some queue made up of a data type I made that stores steps and nodes, and as it traverses the graph it keeps track of the steps. If ever the goal is reached just simply return the steps.
I don't know how to make this work in java so I had to get rid of that idea and I moved on to using that wonky Queue = new LinkedList implementation of a queue. So basically I think it is a normal integer queue, I couldn't get my data type I made to work with it.
So now I have to find a more basic approach so I tried to use a simple counter, this doesn't work because the traversal algorithm searches down many paths before reaching the shortest one so I had an idea. I added a second queue that tracked steps, and I added a couple counters. Any time a node is added to the first queue I add to the counter, meaning I know that I am inspecting new nodes so I am not a distance further away. Once all those have been inspected I can then increase the step counter and any time a node is added to the first queue I add the step value to the step queue. The step queue is managed just like the node queue so that when the goal node is found the corresponding step should be the one to be dequeued out.
This doesn't work though and I was having a lot of problems with it, I am actually not sure why.
I deleted most of my code in panic and frustration but I will start to try and recreate it and post it here if anyone needs me to.
Were any of my ideas close and how can I make them work? I am sure there is a standard and simple way of doing this as well that I am not clever enough to see.
Code would help. What data structure are you using to store the partial or candidate solutions? You say your using a queue to store nodes to be examined, but really the objects stored in the queue should wrap some structure (e.g. List) that indicates the nodes traversed to get to the node to be examined. So, instead of simple Nodes being stored in the queue, some more complex object would be needed to make available the information necessary to know the complete path taken to that point. A simple node would only have information about itself, and it's children. But if you're examining node X, you also need to know how you arrived to node X. Just knowing node X isn't enough, and the only way (I know of) to know the path taken to node X is to store the path in the object that represents a "partial solution" or "candidate solution". If this is done, then finding the length of the path is trivial, because it's just the length of this list (or whichever data structure chosen). Hope I'm making some sense here. If not, post code and I'll take a look.
EDIT
These bits of code help show what I mean (they're by no means complete):
public class Solution {
List<Node> path;
}
Queue<Solution> q;
NOT
Queue<Node> q;
EDIT 2
If all you need is the length of the path, and not the path, per se, then try something like this:
public class Solution {
Node node; // whatever represents a node in you algorithm.
int len; // the length of the path to this node.
}
// Your queue:
LinkedList<Solution> q;
With this, before enqueuing a candidate solution (node), you do something like:
Solution sol = new Solution();
sol.node = childNodeToEnqueue;
sol.len = parentNode.len + 1;
q.add(sol);
The easiest solution in order to track distance during a traversal is to add a simple array (or a map if you vertices are not indexed by integers).
Here is pseudo code algorithm:
shortest_path(g, src, dst):
q = new empty queue
distances = int array of length order of g
for i = 0 to order: distances[i] = -1
distances[src] = 0
enqueue src in q
while q is not empty:
cur = pop next element in q
if cur is dst: return distances[dst]
foreach s in successors of cur in g:
if distances[s] == -1:
distances[s] = distances[cur] + 1
enqueue s in q
return not found
Note: order of a graph is the number of vertices
You don't need special data structures, the queue can just contains vertices' id (probably integers). In Java, LinkedList class implements the Queue interface, so it's a good candidate for your queue. For the distances array, if your vertices are identified by integers an integer array is enough, otherwise you need a kind of map.
You can also separate the vertex tainting (the -1 in my algo) using a separate boolean array or a set, but it's not really necessary and will waste some space.
If you want the path, you can also do that with a simple parent array: for each vertex you store its parent in the traversal, just add parent[s] = cur when you enqueue the successor. Then retrieving the path (in reverse order) is a simple like this:
path = new empty stack
cur = dst
while cur != src:
push cur in path
cur = parent[cur]
push src in path
And there you are …
So Currently I have a program that creates a huffman tree. the tree is made up of "Hnodes" with these fields: right (points to right child) left (points to left child) code (string of integers, ideally the 0's and 1's that will be the huffman code of this node) character (the character contained in the node).
I have created the huffman tree by adding nodes from a linked list - i know the tree was created correctly. As i created the tree, i told the node when i gave it a parent node, that if it was the parent's "right", its code string was 1, if left 0. However obviously after the entire tree is created, each node is only going to have either a 0 or 1, but not yet a string like 00100101. My question is, now that I have this tree, can can I traverse it? I understand the thought would be to give each child its parent's code + the child's own code, but I do not understand how to loop through the tree to accomplish this.
Thank you in advance.
Maybe this?
ExpandBinaryPaths(node, prefix)
1. if node is null then return
2. else then
3. node.binary = prefix concat node.binary
4. ExpandBinaryPaths(node.left, node.binary)
5. ExpandBinaryPaths(node.right, node.binary)
6. return
The idea is you would call this on the root with no prefix... ExpandBinaryPaths(root, "").