Okay. I have a binary tree, and this is what I want to do with it:
For each node in original tree:
If it's not a leaf, replace it with a leaf node.
Do a calculation on the original tree updated with the removed branch.
Revert the node back to how it was (so now the tree is the same as at the beginning).
The problem is this: I am traversing the tree using a stack. If I change the stack.pop() node to a leaf, this does NOT remove any branches in the original tree. It's the same reasoning behind why you can do:
int x=1
int y=x
y++
And x still equals 1. There's a technical term for this but I forgot it.
So how can I edit the nodes in an original tree and still traverse it?
This is basically what I'm doing to traverse the tree right now:
public void iterativePreorder(Node root) {
Stack nodes = new Stack();
nodes.push(root);
Node currentNode;
while (!nodes.isEmpty()) {
currentNode = nodes.pop();
Node right = currentNode.right();
if (right != null) {
nodes.push(right);
}
Node left = currentNode.left();
if (left != null) {
nodes.push(left);
}
//This is where you do operations on the currentNode
}
}
From what I can tell from your question, for every Node you want to calculate something about the tree as if that node was a leaf.
To do this there is no reason to actually make that node a leaf and then reattach it. Instead, your logic can simply remember which node to treat as a leaf for each computation.
Traverse the tree, and for each Node, let's call it outerCurrentNode, once again traverse the tree doing your calculation - but now for each Node, let's call it innerCurrentNode, test to see if outerCurrentNode == innerCurrentNode. If the test returns true, treat that innerCurrentNode as if it's a leaf, ignoring its children.
EDIT: Here's a mock up of what I'm suggesting (untested):
//entry point - called from directing code
public void iterativePreorder(Node root) {
iterativePreorderKernel(root, root);
}
//recursive method - keeps track of root in addition to current Node
private void iterativePreorderKernel(Node root, Node current) {
if (current.left() != null) {
iterativePreorderKernel(root, current.left());
}
if (current.right() != null) {
iterativePreorderKernel(root, current.right());
}
//for each Node in the tree, do calculations on the entire tree, pretending
//the current Node is a leaf
doCalculation(root, current);
}
//calculation method (also recursive) - takes a current Node, plus
//the Node to treat as a leaf
public void doCalculation(Node innerCurrent, Node pretendLeaf) {
//do calculation with inner current node
if (innerCurrent != pretendLeaf) {
if (innerCurrent.left() != null) {
doCalculation(innerCurrent.left(), pretendLeaf);
}
if (innerCurrent.right() != null) {
doCalculation(innerCurrent.right(), pretendLeaf);
}
}
}
I'm using recursion instead of a Stack, but either will work. iterativePreorder() does a traversal, calling doCalculation() for each Node, passing it in along with the root (to keep track of the entire tree). That method then does its own traversal, doing your calculation, but stopping short when it reaches the specially marked Node.
Related
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.)
This is homework; please don't just give me code
I have two methods: remove(T data) and removeRec(Node<T> node, T data).
In its current state, it seems my code only removes the root node of the BST.
#Override
public T remove(T data) {
if (data == null) {
throw new IllegalArgumentException("Data is null");
}
if (root == null) {
throw new java.util.NoSuchElementException("BST is empty");
} else {
size--;
BSTNode<T> dummy = new BSTNode<T>(null);
return removeRec(root, data, dummy).getData(); //This is probably wrong too
}
}
/**
* Helper method to recursively search for, and remove the BSTNode with
* the given data in it
* #param node is the node we're currently at
* #param data is the data we're looking for
* #param temp I have no idea why
* #return node that was removed
*/
private BSTNode<T> removeRec(BSTNode<T> node, T data, BSTNode<T> temp) {
if (compare(data, node.getData()) < 0) {
temp.setLeft(removeRec(node.getLeft(), data, temp));
} else if (compare(data, node.getData()) > 0) {
temp.setRight(removeRec(node.getRight(), data, temp));
} else if (node.getLeft() != null && node.getRight() != null) {
temp.setData(findMin(node.getRight()).getData());
temp.setRight(removeRec(node.getRight(), data, temp));
} else {
if (node.getLeft() != null) {
temp = node.getLeft();
} else {
temp = node.getRight();
}
}
return temp;
}
private int compare(T a, T b) {
return a.compareTo(b);
}
My instructor has told me (as a hint) that I should see what passing in a third argument into the method, in this case, BSTNode<T> temp. I don't understand how that helps though, or how to utilize it. I don't see how using a third argument helps; and I can't find anything online as to why you'd do this either.
There are three main possibilities when you try to remove data from your Binary Search Tree:
data is less than the current node value: Call remove on the left subtree or throw a NoSuchElementException if it is null.
data is greater than the current node value: Call remove on the right subtree or throw a NoSuchElementException if it is null.
data is equal to the current node value.
1 and 2 are pretty straightforward, but 3 has four more cases to consider:
3.1. current node is a leaf: Both left and right subtrees are null. Just replace the reference to the current node in its parent by null.
3.2. current node has only the left child: You need to make the parent of the current node point to the left subtree, thus removing the current point. To do this, you can implement a function that will check if the current point was on the left or right subtree of the parent and replace it accordingly. Calling it would look like this:
replaceNodeInParent(node, node.getLeft(), parent);
3.3. current node has only the right child: Similar to 3.4, but using getRight() instead of getLeft().
3.4. current node has both the left and right children: You should maintain the property of the BST that all nodes on the left are less than the current node and all nodes on the right are greater than the current node. To do so, you should find the smallest value on the right, copy it to the current node, and delete it from the right subtree. Something like this:
BSTNode<T> successor = findMin(node.getRight());
node.setData(successor.getData());
removeRec(node.getRight(), successor.getData(), node);
It looks like your BSTNode doesn't hold a reference to the parent node. If so, I believe that's what the third argument for removeRec should be. You will need a reference to the parent every time you replace the current node, so you can set the parent left or right subtree as needed.
For further reading, you can check this article on Binary Search Trees from Wikipedia.
Iunderstand the basis of a deletion algorithm in a Binary Search tree and have created the following code to delete the largest value from the tree.
public void DelLargest()
{
Node<T> del = this;
boolean child = this.left.empty();
boolean child2 = this.right.empty();
right.DelLargest();
if(child && child2)
this.head = null;
else if(child == true && child2 == false)
this.head = left;
}
Basically what I have is that the recursion runs until 'this' is the rightmost node and then checks two cases, whether 'this' is a leaf, or whether 'this' has a left child. (The other case normally associated with this kind of algorithm is redundant because in finding the node with the largest value, I have gone as right as I can go.) The trouble I am having is getting the current node to then either point to null or to the value at Node left.
Note : This is what my instructor referred to as a "modern" Binary search Tree wherein a vertex or "filled" node and a nil or "empty" node are two subclasses of Interface Node which define the characteristics of each type.
I've managed to narrow the problem down to the fact that I do not have a method that returns a value of a given Node. Working on that now, input would be appreciated.
As suggested in the other answer you should use iterative approach.
In a BST the largest value is the rightmost node.
So do a scan and keep going right until you hit a null.
In the scan keep track of three nodes. (gpnode, pnode, node).
Once the scan is done you will have (gpnode,pnode,null)
Now there are 2 cases.
case 1:
pnode is a leaf. So change the edge (gpnode,pnode) to (gpnode,null)
case 2: (EDITED)
pnode.lChild is not null. Note that pnode.rChild will be null as the search would have terminated at that point.
Now change the edge (gpnode,pnode) to (gpnode,pnode.lChild)
Here is the pseudo code:
public class Node
{
long key;
Node lChild;
Node rChild;
}
public void DelLargest()
{
Node gpnode = null;
Node pnode = null;
Node node = root;
while(node != null) // keep going right until a null is reached
{
gpnode = pnode;
pnode = node;
node = node.rChild;
}
if(pnode.lChild == null) // its a leaf node So change the edge (gpnode,pnode) to (gpnode,null)
{
if(gpnode.lChild == pnode)
{
gpnode.lChild = null;
}
else
{
gpnode.rChild = null;
}
}
else // copy lChild's key to this node and delete lChild
{
if(gpnode.lChild == pnode)
{
gpnode.lChild = pnode.lChild;
}
else
{
gpnode.rChild = pnode.lChild;
}
}
}
You've got the right idea. What you want to do is keep a reference to the right most nodes parent, and the right most nodes left child so then when you delete it you can attach the two.
Here's an iterative solution. This will generally be more efficient than recursion, but if you want recursion you should be able to adapt it:
public void delLargest() {
// get rightmost node's parent
Node<T> current = root;
while(current.right != null && current.right.right != null) {
current = current.right;
}
// get the rightmost nodes left node
Node<T> left = current.right.left;
// attach the parent and left
current.right = left;
// nothing points to the right most node anymore, so it will be garbage collected
}
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)