I have a toString with a helper method to print out the results of a circular linked list class I created. This is it:
/**
* Returns a String version of this.
*
* #return A String description of this.
*/
public String toString(){
String string = "";
DoubleNode<E> current = this.head;
string += stringHelper(this.head);
return string;
}
//Helps the full to string method
private String stringHelper(DoubleNode<E> node){
String string = "";
if(node == null){
return string;
}
System.out.println("Node value: " + node.getValue());
node = node.getNextLink();
if(node == this.head){
string += node.getValue();
return string;
}
else{
string += node.getValue();
return (stringHelper(node.getNextLink()) + ", " + string);
}
}
However, it appears to not be working. I have a test case where it should print out 40, 10, 2, but it prints out only 40, 10. Can anyone help me with this?
I believe you should replace the recursive call stringHelper(node.getNextLink()) with stringHelper(node), as you call node.getNextLink() twice in stringHelper() method which is not right.
I figured it out. Sorry for posting this, as I should have done this on my own. I ended up doing:
/**
* Returns a String version of this.
*
* #return A String description of this.
*/
public String toString(){
String string = "";
DoubleNode<E> current = this.head;
string += stringHelper(this.head);
return string;
}
//Helps the full to string method
private String stringHelper(DoubleNode<E> node){
String string = "";
if(node == null){
return string;
}
string+= node.getValue();
string+= ", ";
node = node.getNextLink();
if(node == this.head){
return string;
}
else{
string += node.getValue();
return (string + ", " + stringHelper(node.getNextLink()));
}
}
Related
I am trying to build a string recursively but the method returns the string before the recursive method is done.
What code should do is when toStringHelper is called it should create a string of all of the elements in the binary search tree in order. I can do this with a print statement with the given code but don't know how to make it into a string that gets returned.
protected static String toStringHelper(BSTNode current, String result) {
if (current != null) {
toStringHelper(current.getLeft(), result);
result += current.getData().toString() + "\n";
toStringHelper(current.getRight(), result);
}
return result;
}
Can't you just append directly to result? It should build the same.
protected static String toStringHelper(BSTNode current, String result) {
if (current != null) {
if(current.getLeft() != null) result += toStringHelper(current.getLeft(), result);
result += current.getData().toString() + "\n";
if(current.getRight() != null) result += toStringHelper(current.getRight(), result);
}
return result;
}
Actually String result argument is not needed . You can check below code .
protected static String toStringHelper(BSTNode current)
{
if (current == null)
{
return "";
}
String result="";
result += toStringHelper(current.getLeft());
result += current.getData().toString() + "\n";
result += toStringHelper(current.getRight());
return result;
}
This is how it is called from main()
BSTNode root = new BSTNode();
root.setData("Root");
root.setLeft(new BSTNode(null, null, "Left"));
root.setRight(new BSTNode(null, null, "Right"));
String res = toStringHelper(root);
System.out.println("Res is " + res);
Here is the o/p
Res is Left
Root
Right
I want to make an in order transversal of a binary tree. I made this method:
public String inorder()
{
String inorder = "";
return recrInorder(this.root, inorder);
}
then i have a helper method:
private String recrInorder(Node curr,String string)
{
if(curr == null)
{
return "";
}
//Go through left
recrInorder(curr.getLeft(), string);
string = string + curr.getData() + ", ";
//Go through right
recrInorder(curr.getRight(), string);
return string;
}
This will only print the root, i want the whole list printed.
In Java parameters are passed by value for object reference so assigning new value to your input parameter named string will not change its value outside of that function.
You need to change your code like this
private String recrInorder(Node curr,String string)
{
if(curr == null)
{
return string; // preserve previously calculated value
}
//Go through left
string = recrInorder(curr.getLeft(), string);
string = string + curr.getData() + ", ";
//Go through right
string = recrInorder(curr.getRight(), string);
return string;
}
public String inorder() {
return recrInorder(this.root);
}
private String recrInorder(Node curr) {
if (curr == null) return "";
return recrInorder(curr.getLeft()) + curr.getData() + ", " + rectInorder(curr.getRight());
}
Given a parent, left child, and right child relationship, the traversal of the tree is dependent on when you visit the parent and access the String value.
Given the root of the tree call it as follows:
String s = traverse(root, "");
System.out.println(s);
public static String traverse(Node n, String s) {
if (n == null) {
return s;
}
// s += n.value; // uncomment this assignment for preorder traversal
s = traverse(n.left,s);
// s += n.value; // uncomment this assignment for inorder traversal
s = traverse(n.right,s);
// s += n.value; // uncomment this assignment for postorder traversal
return s;
}
So in your method, you could pass a flag or enum and caveat the assignment based on that value, thus adapting your method to any traversal.
As a programming exercise I need to rewrite some existing methods and classes that make up a binary tree. (The method signatures and constructors have to stay the same). Somehow I don't really seem to understand what I have done here.
Does the toString method have to public because it overwrites the Object class's toString method? And how can I avoid the nulls from being returned?
Here is the code I have come to so far:
Tree Class
Node root = null;
void addNode(int val) {
Node newNode = new Node(val);
root = newNode.addNode(root, val);
}
Node Class
Node(int val) {
val = val;
left = null;
right = null;
}
Node addNode(Node focusNode, int newNodeVal) {
if (focusNode == null)
return this;
if (newNodeVal == focusNode.val)
return focusNode;
if (newNodeVal < focusNode.val)
focusNode.left = this.addNode(focusNode.left, newNodeVal);
else
focusNode.right = this.addNode(focusNode.right, newNodeVal);
return focusNode;
}
public String toString() {
return this.left + " " + this.val + " " + this.right;
}
Use a StringBuilder to store the String representation of the node and append the data of the children nodes only in the specific node is not null. Here's an example using infix navigation on the nodes:
public String toString() {
StringBuilder sb = new StringBuilder();
if (this.left != null) {
sb.append(this.left);
sb.append(' ');
}
sb.append(this.val);
if (this.right != null) {
sb.append(' ');
sb.append(this.right);
}
return sb.toString();
}
public String toString() {
if(this.left==null){
return this.val + this.right;
} else if (this.right==null){
return this.left + this.val;
} else if (this.left == null && this.right == null){
return "";
} else {
return this.left + " " + this.val + " " + this.right;
}
}
You assign your nodes to null to start, and your toString method assumes that they have been altered. Imagine a tree where you added 5, then 3. Then called toString on the tree. It will try to print the node, 5 is the value, left is 3, right is null. When you try to call
return this.left + " " + this.val + " " + this.right;
You are saying to print
3 5 NULL
You can initialize left and right with an empty Node object (with no val) and when you print it you will see null as the val of an empty Node:
Node(Integer val) {
this.val = val;
left = new Node(null);
right = new Node(null);
}
This only works if you make val an Integer.
There is also a bug in your code:
val = val will leave this.val untouched. You have to use this.val = val;
toString() is overridden not overwritten. It has to return a String and you can't really avoid nulls if your Node is a leaf.
What you can do is writing toString() in a way it can be meaningful to have a null as val like this:
public String toString() {
return "#{val = " + val + ", left = " + left + ", right = " + right + "}"
}
Please note that this will traverse your tree recursively so to print your tree you only have to call root.toString().
It only prints out one item.
It is suppose to print the contents of the tree in ascending order
public String toString()
{
return toString (_root);
}
private String toString(BSTnode root)
{
if (root == null)
return "";
toString(root._left);
toString(root._right);
return root._data.toString();
}
How do you want to show them?
You need to append the Strings, for example.
private String toString(BSTnode root)
{
StringBuilder builder = new StringBuilder();
if (root == null)
return "";
builder.append(toString(root._left));
builder.append(toString(root._right));
return builder.append(root._data.toString()).toString();
}
or just use a concatenation on strings.
private String toString(BSTnode root)
{
String result = "";
if (root == null)
return "";
result += toString(root._left);
result += toString(root._right);
result += root._data.toString()
return result;
}
//Helper
public String toString(){
return "<" +toString(root) + ">";
}
//recursively printing out the nodes
public static String toString(Node r){
if(r==null)
return "";
else
return toString(r.left) + " " +r.value + " " +toString(r.right);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
// Helper
public String toString() {
return "<" + toString(this) + ">";
}
// recursively printing out the nodes
public static String toString(TreeNode r) {
if (r == null)
return "";
else
return r.val + " " + toString(r.left) + " " + toString(r.right);
}
}
public String toString(){
return toString (_root);
}
public String toStringAscending(BSTnode node)
{
if (node == null) return "";
return toStringAscending(node.left) + node._data.toString() + toStringAscending(node.right);
}
I need to print out a QuadTree. The problem is that I don't know how to implement an incrementing shift in order to be able to visualize the tree structure.
Currently I just see each level of nodes at a new line. However, it's complicated to use this visualization for working with a tree.
#Override public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
String SHIFT = System.getProperty(" ");
if (_children != null) {
String content = "";
for (QtreeNode<E> node : _children) {
content += node.toString() + ",";
}
result.append("{" + SHIFT + NEW_LINE +
content.substring(0, content.length()) +
SHIFT + NEW_LINE + "}");
} else if (_items != null) {
String content = "";
for (E item : _items) {
content += item.toString() + " ";
}
result.append("[" + content + "]");
}
return result.toString();
}
Provide separate toStringWithIndent(int depth) method for your tree Nodes, and call it inside overridden toString(). This method will call same one for each subnode, etc. recursively.
UPD Some example
class Node {
private String name;
private List<Node> children;
#Override
public String toString() {
String s = name;
for(Node n: children) s += children.toStringWithIndent(1);
return s;
}
private String toStringWithIndent(int depth) {
// same as toString() but with indent
String s = indentFor(depth) + name;
for(Node n: children) s += indentFor(depth) +
children.toStringWithDepth(depth + 1);
return s;
}
private static String indentFor(int depth) {
StringBuilder b = new StringBuilder(depth);
while(depth-- > 0) {
b.append(" ");
}
return b.toString();
}
}