So I'm trying to put an element in a binary tree (not a search tree) in java. I looked everywhere, and all I can see are algorithms for inserting it into a binary search tree (and I want a simple binary tree). Given the value of the parent node, I need to set the left and right children. My plan looks like this:
public void addLeft(E elem, E parentVal) {
//Find node with parentVal
//Create node with element elem (call it newNode)
//Set the left child of the node with parentVal as newNode
}
The last 2 steps are fairly simple, so my real problem is finding the node with a given value.
In a search tree, it is an easy task, but in a normal binary tree, I don't know how to do it. I understand that it won't be efficient; as far as I know, to add an element to a given node in a normal binary tree, we have to traverse the entire tree to find that node. Any suggestions on how to do this? Assume there will be no repeats of numbers (all nodes have a unique element). I've tagged this as algorithm/pseudocode, so just a basic idea is all I need to get started (although code is appreciated as well).
Here is a simple way of recursively traversing the tree and stopping when parentVal is found:
// returns true if the element has been added to this subtree
public boolean addLeft(E elem, E parentVal) {
if (this.equals(parentVal)) {
//Create node with element elem (call it newNode)
//Set the left child of the node with parentVal as newNode
return true;
} else if (leftChild != null && leftChild.addLeft(elem, parentVal)) {
return true;
} else {
return rightChild != null && rightChild.addLeft(elem, parentVal);
}
}
This is assuming that a node has access to its children through leftChild / rightChild.
Found this in Google code and in github search took me to this Java implementation
Another quick raw write-up implementation is the python implementation of Binary tree. The heading for link is misleading, but check the entire write-up.
From the link here is a high level psuedo.,
class Node:
...
def insert(self, data):
"""
Insert new node with data
#param data node data object to insert
"""
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
else:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
Related
I will receive something like:
public int count (Tree myTree){
}
I already have the Tree definition, getLeft(), getRight() methods.
I have seen some examples, but always they receive a node as parameter, I need to receive the Tree as parameter.
Could anyone please help me? I'm new on this topic.
Thanks
Here Tree is the node class itself, meaning the name is given differently.
So myTree parameter is a node itself of the given Binary Tree, here pointing to the root in the given function.
Now Tree and the node class itself in the picture below, where the right child and left child and the data of the current node are stored.
So to find out the number of nodes of a given tree,
You have to first check if the given myTree is null or not, meaning if the given myTree doesn't have any Root node only.
Then you have to return 0.
int count(Tree myTree)
{
if (myTree == null)
return 0;
int res = 0;
if (myTree.left != null && myTree.right != null)
res++;
res += (count(myTree.left) + count(myTree.right));
return res;
}
Hope it helps :D
A tree in fact is defined by its root node, but let's just say you implemented the Tree in your own way :p and that you have a function to get the root getRoot(), you can use recursion as it follows to count the number of nodes in your tree (we assume that for a node you can access the children with getLeft() and getRight(), you have to implement a function to construct a tree from a node constructTree(Node root)):
public int count (Tree myTree){
Node root = myTree.getRoot();
return root != null ?
1 + count(constructTree(root.getLeft()) +
count(contructTree(root.getRight()))
: 0;
}
Here in count (Tree myTree){ }
Tree is the Node class only and you'll receive root node as a parameter which here is myTree
Because without root node it is impossible to access tree.
And in java Collections there is no such thing as Tree. So rest assured you are on right track.
Assuming Tree == Node as you have described your problem, then one approach is to use recursion:
public static int count(Tree tree) {
Tree left = tree.getLeft();
Tree right = tree.getRight();
return 1 +
(left != null ? count(left) : 0) +
(right != null ? count(right) : 0);
}
How do I write the code to find a certain node. Specifically how do I say a node was visited after I check it?
public Iterator<T> pathToRoot(T targetElement, BinaryTreeNode<T> current)
throws ElementNotFoundException
{
Stack<BinaryTreeNode<T>> myStack = new Stack<>();
if (current == null)
return null;
if (current.element.equals(targetElement)) //found it
{
myStack.push(current); //adds the current element to the stack
}
// mark as visited
//mark node also as found
// return the found element
if (current.hasLeftChild() || current.hasRightChild()) //if the current node has a left or right child
{
// mark node as visited
}
if (current.hasLeftChild())//if the current node has a left child node
pathToRoot(targetElement, current.getLeft()); // check the left child node
if (current.hasRightChild())//same thing as above but for the right
pathToRoot(targetElement, current.getRight());
if(current != targetElement && /*node has been visited*/)
myStack.pop(); // pop node from the stack
return myStack.toString(); //return string of path to root
}
/using a dfs search to find a node/
The sole purpose of marking a graph node as visited is to make sure you won't get into an infinite loop, because a graph can contain a cycle.
A binary tree is a special kind of a graph, that doesn't contain cycles, therefore there's no need to mark nodes as visited when you're doing traversal.
Also, usually binary trees are ordered in a way that the current node contains value X, its left sub-tree has nodes that have values less than X, and its right sub-tree has nodes that have values greater than X. This allows having searches that take logarithmic time, in your demonstrated code you don't seem to utilize that.
So, I think you don't have a good understanding of how binary trees work and you should research a little more, before implementing this functionality.
So I know for a binary tree the general way to preorder traverse it is like this
void displayPreOrder(TreeNode node)
{
if(node != null)
{
displayPreorder(node.left);
displayPreorder(node.right);
System.out.println(node.value);
}
}
But I'm having trouble trying to wrap my head around a preorder traversal of a quadtree. I've tried to find some resources, but left empty handed. Any hint?
The code you posted is for a postorder traversal of a binary tree. For a quadtree, you just need to visit all children instead of just left and right.
For simplicity, I'll assume that TreeNode defines a method children() that returns an iterator or a List of the node's children in some well-defined order. If that's not available, just iterate through the children using whatever mechanism is available.
void displayPreOrder(TreeNode node)
{
if(node != null)
{
// visit the root first for pre-order
System.out.println(node.value);
for (TreeNode child : node.children()) {
displayPreorder(child)
}
}
}
(P.S. This works for binary trees as well, given the right iteration mechanism.)
So I've been stuck for hours trying to figure out this problem.
Given a randomly generated BST and using the method header:
public E higher(E elt)
Where elt is a randomly generated value within the tree's range, I need to find the least element in the set greater than elt.
Nodes contain left links and right links, but no parent link.
The tree in the linked image reads with the root being the leftmost node
BST.
So if elt is 27, then I want to return the node containing 28.
I need to run this in O(logn) time, and everything I've tried has not worked.
I'm not looking for someone to do my homework for me, but I have no clue what to do at this point.
I can provide more detail and source code if it's needed.
Edit: I'll put this here, though it's woefully inadequate. I feel as though this would be easier if I could do this recursively but I can't think of a way to do that.
Node n = root;
//need to get this into a loop somehow and break out when I've found
//the right value
int c = myCompare(elt, ((E) n.data));
if (c < 0) {
n = n.left;
//now I need to compare this against any children
} else if (c > 0) {
n = n.right;
//now I need to compare this against any children
}
return ((E)n.data);
This depends on the fundamental property of BSTs: the left child is less than the parent, the right child is greater than the parent. If you look at a sample BST you will quickly notice a few properties, and you can see why the following algorithm will work.
If the current node is less than the given value, move right, otherwise move left. If you reach a point where moving left will give you a value that is too low (or you hit a leaf) then you found the correct node. Or, in pythonic pseudo-code:
while (true):
if (node.value <= elt):
node = node.right
else:
if (node.left.value < elt):
return node.value
else:
node = node.left
The pseudo-code obviously needs to check for errors, if a node is a leaf, etc., but this general algorithm will give you the expected output in the desired time complexity (assuming a balanced BST).
One possible approach is to find the specified node and to get the next least node from there (if you're allowed to use helper methods).
If we say that the root node is 'n' and we know that the desired value is inside the BST, then you can traverse through it to find the node that contains the given value with something like this:
public Node search(Node n, E obj)
{
if(obj.compareTo(n.getValue()) > 0)
{
return search(n.getRight(), obj);
}
else if(obj.compareTo(n.getValue()) < 0)
{
return search(n.getLeft(), obj);
}
else
{
return n;
}
}
If the objective were to retrieve the least value from a binary search tree, a simple recursive method like this would work:
public Node getLeast(node n)
{
if(n.getLeft()==null)
{
return n;
}
return getLeast(n.getLeft());
}
Using the principles of a binary search tree, we know that the least value greater than a given node is just the least node after the right child of the given node. So, we can just use this method to obtain the desired value:
getLeast(search(n,elt).getRight());
I am hopelessly lost when it comes to recursive functions. I am required to create a recursive function to traverse a binary tree and insert a new node in between specific values. Would i need to recopy my traverse function and modify it in every other function that i use it in? Would someone please evaluate the traverse function?
I think my traversing code is alright.
Node traverse (Node currentNode){
if (!currentNode.left.equals(null)){
traverse (currentNode.left);
return currentNode.left;
}
if (!currentNode.right.equals(null)){
traverse (currentNode.right);
return currentNode.right;
}
return currentNode;
}
When it comes to binary trees, there are several different types of traversals that can be done recursively. They're written in the order they're referenced then visited (L=Left child, V = visit that node, R = right child).
In-order traversal (LVR)
Reverse order traversal (RVL)
Preorder traversal (VLR)
Postorder traversal (LRV)
Your code appears to be performing the postorder traversal method, but you're getting a few things mixed up. First, the node is what you want to traverse; the data is what you want to visit. Second, you have no reason to return the node itself, in the way that this is implemented. Your code doesn't allow for a condition to say, 'I'm looking for this particular data, do you have it Mr. Node#0xdeadbeef?', which would be found with some sort of extra search parameter.
An academic BST traversal only prints the nodes itself. If you wanted to add a search functionality, it's only one more parameter, as well as an additional check for the right node.
Here's a snippet:
// Academic
public void traverse (Node root){ // Each child of a tree is a root of its subtree.
if (root.left != null){
traverse (root.left);
}
System.out.println(root.data);
if (root.right != null){
traverse (root.right);
}
}
// Search with a valid node returned, assuming int
public Node traverse (Node root, int data){ // What data are you looking for again?
if(root.data == data) {
return root;
}
if (root.left != null && data < root.data) {
return traverse (root.left, data);
}
if (root.right != null && data > root.data) {
return traverse (root.right, data);
}
return null;
}
It seems like you are traversing in the preorder methodology, but i am a little skeptical as to what exactly you wish to accomplish without actually comparing your current node with some base value that defines u have reached ur destination. I would suggest drawing out a simple tree and visualizing the steps. Then try to put that into code.
A recursive function returns the value of itself with a modified parameter, or a termination (exit) condition. eg, Factorial:
int factorial( int param ) {
if ( param > 1 ) {
return param * factorial( param -1 );
} else {
return 1;
}
}
In your code, you call a 'traverse' but then do nothing with the result...
When your recursive function ends, your final return will be first left child if it exists, else the first right child if it exists, else the root node.
Please give more detail as to why you need to traverse the tree (also, not sure what you meant by "copy the function and modify it in every other function", the whole idea of a function is to code-once-call-many)