building a string recursively in java using a Binary search trees data - java

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

Related

Binary Tree toString prints hashcode even after override

I made a program that inserts characters (letters) into a binary search tree. I am not encountering any errors but when I call the toString method, it only prints a part of the output with the hashcode of ht=10 [K=G R=BTNode#5b6f7412]. I might have overlooked something so it would be greatly appreciated if you could help me out. Thanks!
Expected Output (not the exact output but in this format)
ht=2 [K=A L=[K=B R=[K=C]] R=[K=D L=[K=E]]]
toString method
public String toString()
{
String s = "";
BTNode<T> n = root;
if (n == null)
{
return "";
}
if (n != null)
{
s = "ht=" + height + " [K=" + n.info;
if (n.left != null)
{
s = s + " L=" + n.left.toString() + "]";
}
if (n.right != null)
{
s = s + " R=" + n.right.toString() + "]";
}
}
return s;
}
Main Class
public static void main(String args[])
{
BST<Character> bst = new BST<>(); // instantiate BST object
// insert values to bst
bst.insert('A');
bst.insert('B');
bst.insert('C');
bst.insert('D');
bst.insert('E');
bst.insert('F');
// print bst1
System.out.println(bst.toString());
}
You have to write a method with the exact signature public String toString() in BTNode.
Writing public String toString(BTNode<N>) accomplishes nothing.

Using a recursive method to return an inorder string in java?

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.

Binary Node Tree, wrong father and sons

I'm having a hard time printing the following tree:
----------t1:----------
tree:(((1),2,(3)),4,((5),6,(7,(8))))
----------t2:----------
tree:(((1),2,((3),4)),5,(6,(7,(8))))
----------t3:----------
tree:((1),2,(3,(4,(5,(6,(7,(8)))))))
----------t4:----------
tree:((((((((1),2),3),4),5),6),7),8)
where "father" have no parentheses and each "son" has a bracket depends on the depth,the picture are the trees with depth.
here is my code:
private String toString(String acc,int length){
if (left != null)
acc =left.toString(acc, length + 1)+")"+",";
// Adding two spaces 'length' times
for (int i = 0; i < length; i++) {
acc +="";
}
// adding the object data and new space
acc += this.data.toString();
if (right != null)
acc = "("+right.toString(acc, length + 1);
return acc;
}
public String toString() {
return "("+toString("", 0)+")";
}
which instead prints:
----------t1:----------
tree:(((((1),23),45),678)
----------t2:----------
tree:(((((1),23),4),5678)
----------t3:----------
tree:(((((((1),2345678)
----------t4:----------
tree:(1),2),3),4),5),6),7),8)
in the added picture, the tree is demonstrated with depth
Actually, every node has an opening and closing parenthesis. As Stefan commented, you don't need the depth. Here's the code:
public String toString() {
String out = "(";
if (this.left != null) {
out += left.toString() + ",";
}
out += this.data;
if (this.right != null) {
out += "," + right.toString();
}
return out + ")";
}

Recursive toString binary tree output

So I want my printout of my binary tree to read like [A B C D E F] but I keep ending up with an extra space and I can't use subString to remove it. What is the best way to approach this?
public String toStringInOrder() {
output = "";
output += printInOrder(root);
if(output.length() < 1) {
return "[]";
} else {
return "[" + output.substring(0, output.length() - 1) + "]";
}
}
private String printInOrder(Node current) {
if(current != null) {
printInOrder(current.left);
output += current.value + " ";
printInOrder(current.right);
}
return output;
}
If your only concern is removing the extra space at the end you could replace:
return "[" + output.substring(0, output.length() - 1) + "]";
with:
return "[" + output.Trim() + "]";
Another approach I might take is filling a List with the ordered values, and then you can have a greater control of how you format the ordered values as a string.
If you can't use substring or similars, do a "look for maximum node" search (cheap log(n) operation), save that node and add an if statement on your output additions that checks if the node whose info has to be added isn't the last one. In that case, add the value without the space.
Node last = max(root);
private Node max(Node x){
if (x.right == null)
return x;
return max(x.right);
}
private String printInOrder(Node current) {
if(current != null) {
printInOrder(current.left);
if(!current.equals(last))
output += current.value + " ";
else
output += current.value;
printInOrder(current.right);
}
return output;
}
I discovered the answer I needed after some diagramming and trial and error.
private String printPreOrder(Node current) {
if (current != null) {
output += current.value;
if (current.left != null) output += " ";
printPreOrder(current.left);
if (current.right != null) output += " ";
printPreOrder(current.right);
}
return output;
}
Some changes to the inOrder and postOrder garners similar results. Thanks to all for the help!

Binary Search Tree: Recursive 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);
}

Categories

Resources