finding depth of node in a binary tree not BST - java

I have a binary tree not bst ,I need to find the depth of a node in that binary tree
Is there any other way to achieve other than level order traversal using some dilimeter to main the count of level .
As input I have the root node of the tree and one of the node of the tree for which i need find the depth.
I want to have some recursive way to find this

If you don't want to do a BFS you can do a DFS (and you can also do it recursively).

pseudo-code for DFS function, the first call will be DFS(root).
DFS(node v, integer d)
visited[v] = true
depth[v] = d
for each u such that u is adjacent to v
if visited[u] == false
DFS(u, d+1)

Try passing an additional parameter in your recursive function to indicate depth.

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.

How to construct a unordered binary tree from text file

Dear Friends I am an intermediate java user. I am stuck in a following problem. I want to construct a unordered binary tree [or general tree having at most two nodes] from a multi line (let say 40 lines) text file. The text file is then divided into two halfs; let say 20:20 lines. Then for each half a specific (let say hash) value is calculated and stored in the root node. So each node contains four elements. Two pointers to the two children (left and right) and two hashes of the two halfs of the original file. Next for each half (20 lines) the process is repeated until at each leaf we have a single line of text. Let the node have
public class BinaryTree {
private BinaryTreeNode leftNode, rightNode;
private String leftHash,rightHash;
}
I need help for writing the tree construction and searching functions. Well searching is performed by entering a line. Then hash code is created for this query line and compared against the two hashes saved at each node. If the hash of query line is close to leftHas then leftNode is accessed and if the hash of query line is close to rightHash then rightNode is accessed. The process continues until an exact hash is found.
I just need the tree construction and search teachnique. The hash comparison etc are not a problem
You'll need to start by reading the file into a string.
The first character in the string could be used as the root. Root + 1 would be the left, root + 2 would be the right
Consider left node of the root (Root + 1), you could also consider this as Root + N. Meaning that the right node would be Root + N + 1.
You can now recursively solve this problem by establishing which Node you are currently on, and setting the left and right now respectively.
So lets think about it,
You have the root node, left node, and right node established. At this point you have used 3 letters/numbers (it really doesnt matter if it is unordered). The next step would be to move down one level and start filling the left, you have the root, you need left and right nodes. Then move to the right node, do the left and right node of this and so on and so forth.
Think about that for a little bit and see where you get.
Cheers,
Mike
EDIT:
To search,
Searching a binary tree is also a recursive theme. (I thought you previously said the tree was unordered, which may change how the tree is laid out if it is suppose to be order).
If it is unordered, you can simply recurse the tree in a manner such that
A.) Check root node
B.) Check left node
C.) Continue checking left nodes until either there is a match, or no more left nodes to check
D.) Recurse back 1, check right node
E.) Check left nodes,
F.) Recuse back, check right node
This theme will continue until eventually you have checked ALL left nodes first, and then the right nodes. The KEY to this, is at any point you have a root node, go left first, then right. (I forget what traversal type this is, but there are others if you wish to implement them over this, i personally think this is the easiest to remember).
You will then repeat for right child of Root node.
If at any time you get a match, exit.
Remember this is recursive, so make sure you think your way through this step by step. It is recursive by definition, in that you will always do steps x,y,z for each part of the tree.
To beat a dead horse, lets look at just 3 nodes to start.
(simplified)
First the root,
if(root == (what your looking for))
{
return root
}
else if(root.leftNode == (what your looking for))
{
return root.leftNode
}
else if(root.rightNode == (what your looking for))
{
return root.rightNode
}
else
{
System.out.println("Value not found")
}
If you have 5 nodes, that would be root would have a left and right, and the root.leftNode would have a left and right... You would repeat the steps above on root.leftNode also, then search root.rightNode
If you have 7 nodes, you would search ALL of root.leftNode and then recurse back to search root.leftNode.
I hope this helps,
pictures work much better in my opinion when talking about traversing trees.
Perhaps look here for a better visual
http://www.newthinktank.com/2013/03/binary-tree-in-java/

Scan tree structure from bottom up?

If given the following tree structure or one similar to it:
I would want the string ZYXWVUT returned. I know how to do this with a binary tree but not one that can have more than child nodes. Any help would be much appreciated.
This is called a post-order traversal of a tree: you print the content of all subtrees of a tree before printing the content of the node itself.
This can be done recursively, like this (pseudocode):
function post_order(Tree node)
foreach n in node.children
post_order(n)
print(node.text)
If you are maintaining an ArrayList (say node_list) to track the number of nodes branching of from the current tree node, you can traverse the tree from the root till you find a node that has an empty node_list. This way you will be able to identify the leaf nodes of the tree. A recursive approach would work for this case. I haven't tested the code but I believe this should work for what you have asked:
If you are maintaining something similar to the class below to build your tree:
class Node {
String data;
ArrayList<Node> node_list;}
The following recursive function might be what you are looking for:
public void traverse_tree(Node n){
if(n.node_list.isEmpty()){
System.out.print(n.data);
}
else{
for(Node current_node:n.node_list){
traverse_tree(current_node);
}
System.out.println(n.data);
}
}
Essentially what you are looking at is the Post-order Depth First traversal of the tree.
something like this should do it
public void traverse(){
for(Child child : this.children){
child.traverse();
}
System.out.print(this.value);
}

Traversing a Huffman Tree

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, "").

Find the longest path between any two nodes

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.

Categories