How to Pretty Print a Binary Tree?
I'm trying to display a Binary Tree in such a way:
________26
___13_________2
1_______4 3_________1
(without the underscores)
however I cannot figure out the display method.
class BinaryNode
//Constructors
BinaryNode leftChild, rightChild;
Object data;
BinaryNode()
leftChild = null;
data = null;
rightChild = null;
BinaryNode( Object d, BinaryNode left, BinaryNode right)
leftChild = left;
data = d;
rightChild = right;
//Height
public static int Height(BinaryNode root)
if (root == null)
return 0;
if ((Height(root.leftChild)) > Height(root.rightChild))
return 1 + Height(root.leftChild);
return 1 + Height(root.rightChild);
//Count
public static int Count(BinaryNode root)
if(root==null)
return 0;
return 1 + Count(root.leftChild) + Count(root.rightChild);
//Display
public static void Display(BinaryNode root)
int level = 2^(Level(root)-1)
for (int i = 1; i<Height(root)+1; i++)
System.out.printf("%-4s%
Display(root, i);
System.out.println();
public static void Display(BinaryNode root, int level)
if (root!=null)
if(level==1)
System.out.print(root.data + " ");
else
Display(root.leftChild, level-1);
Display(root.rightChild, level-1);
//Level
public static int Level(BinaryNode root)
if(root==null)
return 0;
if(root.leftChild == null && root.rightChild == null)
return 1;
return Level(root.leftChild) + Level(root.rightChild);
Edited by: 815035 on Nov 23, 2010 12:27 PM
The example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
Unfortunately it is also quite difficult to accomplish using System.out.print statements.
You have to print out the root of the tree first (its at the top)
However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
So you will need to traverse the tree at least twice.
Once to work out the offsets, and again to print out the values.
The working out of offsets would have to be a depth search traversal I think
The printing of the values in this fashion would be a breadth first traversal.
I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
ie the root was on the left, the leaves of the tree on the right of the screen.
That meant you could do an inorder depth traversal of the tree to just print it once.
hope this helps,
evnafets
Similar Messages
-
How to pretty print XML alerts
Hi!
I'd like to generate mail alerts in OSB which include a XML content. I need XML to be human friendly printed (that is with indentation) but XML is printed in a single line.
Is there any way to pretty print XML content in alerts (and also in alerts emails).
Thank you in advance.The example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
Unfortunately it is also quite difficult to accomplish using System.out.print statements.
You have to print out the root of the tree first (its at the top)
However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
So you will need to traverse the tree at least twice.
Once to work out the offsets, and again to print out the values.
The working out of offsets would have to be a depth search traversal I think
The printing of the values in this fashion would be a breadth first traversal.
I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
ie the root was on the left, the leaves of the tree on the right of the screen.
That meant you could do an inorder depth traversal of the tree to just print it once.
hope this helps,
evnafets -
How to pretty printer of a code in enhance framework of a standard FM
Hi,
I have written a code in a <b>enhancement point of a standard Function Module</b>. But i am unable to pretty printer that portion of code. Doed any one have any idea how to do that??
Thanks & Regards,
Abhishek SarkarHi,
Pritty printer gives a pritty view to your code, so that it can be easily readable.
You can set the functionality of pritty printer by doing some setting.
The path for setting is
Utilities>Setting>ABAP Editor-->Pritty Printer.
Thanks. -
How to design databse for binary tree
kindly help in desiging databse for binary tree and also to retrive data from database.
Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.
-
Hi, I have to pretty print a binary tree composed of "key" values like 75, 70, 15, 2, etc. I have no idea how to create a dynamic method that can output a tree in the order that they are in. The tree is supposed to look like this:
15
37
13
75
90
58
2
70
24The 15 is supposed to be in the top middle of the tree. Can anyone give me any help or hints to get started? Thanks.I guess you mean this
15
13 37
2 24 75
58 90
70 -
Creating non binary trees in Java
Hi everybody actually i am used in creating binary trees in java,can u please tell me how do we create non binary -trees in java.
Hi,
Can u let us know the application area for Non binary tree.
S Rudra -
Hi guys i am used in creating binary trees ,tell me how do we create non binary trees in java.
public class Node {
private final Object payload;
private final Set<Node> children;
public Node(Object payload) {
this.payload = payload;
children = new HashSet<Node>();
// now add methods to add/remove children, a method to do something with the payload (say,
// a protected method that passes the payload to a method specified by some kind of interface),
// and methods to recurse over children.
}Actually rather than using Object probably should have generic-ized the class, but whatever. -
How to crossover this binary tree..?
You can view detail http://www.codeguru.com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
[nha khoa|http://www.sieuthi77.com/main/nhakhoa.html] .com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
I have these classes which model a tree (binary). the thing is i cant figure out how i can set the elements of individual nodes in that tree. i can get individual elements but i cannot set them due to the strucutre of the tree and how it is implemented. The changes that I make to these classes should be as less as possible, because i have an algorithm which generates the tree structure randomly, plus i can evaluate the tree easily by using recursion. The only left thing to do is CROSSOVER but how?!?
here are the classes which model my binary tree:
Code:
public abstract class Node implements Cloneable{
abstract double evaluate(VariableInput v);
abstract String print();
abstract int getNumberOfNodes();
abstract ArrayList<Object> getChildren();
@Override
public Node clone(){
Node copy;
try {
copy = (Node) super.clone();
} catch (CloneNotSupportedException unexpected) {
throw new AssertionError(unexpected);
//In an actual implementation of this pattern you might now change references to
//the expensive to produce parts from the copies that are held inside the prototype.
return copy;
Code:
public class UnaryNode extends Node {
private UnaryFunction operator;
private Node left;
public UnaryNode(UnaryFunction op, Node terminal) {
operator = op;
this.left = terminal;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + ")";
return r;
void setLeft(Node left) {
this.left = left;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes();
Node getLeft() {
return left;
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
return arr;
Code:
public class BinaryNode extends Node {
private BinaryFunction operator;
private Node left;
private Node right;
public BinaryNode(BinaryFunction op, Node left, Node right) {
operator = op;
this.left = left;
this.right = right;
public String print(){
String r = "(" + operator.toString()+ " " + left.print() + " " + right.print()+")";
return r;
public void setLeft(Node left){
this.left = left;
public void setRight(Node right){
this.right = right;
@Override
int getNumberOfNodes() {
return 1 + left.getNumberOfNodes() + right.getNumberOfNodes();
Node getRight() {
return right;
Node getLeft() {
return left;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(this);
arr.addAll(left.getChildren());
arr.addAll(right.getChildren());
return arr;
public class NumericNode extends Node{
private double value;
public NumericNode(double v){
value = v;
@Override
double evaluate(VariableInput c) {
return value;
public String print(){
String r = "" + value;
return r;
@Override
int getNumberOfNodes() {
return 1;
@Override
ArrayList<Object> getChildren() {
ArrayList<Object> arr = new ArrayList<Object>();
arr.add(new NumericNode(value));
return arr;
}p.s. I have this get children method which return a list of REFERENCES to all the nodes in the tree, but if i change any of them it wont have an effect to the tree itself because they are references.
Any ideas or codes will be much appreciated. Thanks!What? Changes to what a node is referencing will be reflected in the tree, unless your getChildren is returning a copy, like in NumericNode.
Kaj -
Binary Tree search and print methods
Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
public class TreeNode
public static String empName = null;
public static int empNumber;
public static String nextRec = null;
TreeNode left;
String Name;
int Number;
TreeNode right;
public static void main(String[] args)
VRead in = new VRead();
VWrite out = new VWrite();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public static void inputInfo(VRead in, VWrite out)
out.write("Enter Employee Name: ");
empName = in.readString();
out.write("Enter Employee Number: ");
empNumber = in.readInt();
System.out.println();
System.out.println();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public TreeNode(String empName, int empNumber)
Name = empName;
Number = empNumber;
left = null;
right = null;
public class Tree
TreeNode Root;
public void Tree(String RootNode)
// Errors come from next line
Root = new TreeNode(RootNode, Name, Number);
public void Insert(String Name, int Number)
InsertNode(Root, Name, Number);
public void InsertNode(TreeNode t, String empName, int empNumber)
if (t == null)
t = new TreeNode(empName, empNumber);
else
if (empName.compareTo(t.Name) < 0)
InsertNode(t.left, empName, empNumber);
else if (empName.compareTo(t.Name) > 0)
InsertNode(t.right, empName, empNumber);
else if (empName.compareTo(t.Name) == 0)
System.out.println("Entered node that was already in Tree");
}im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method tooJust having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
FWIW
I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
*Before anyone flames, it's a joke
G -
How to remember the path while traverse a binary tree?
Hi, again, I have difficulty handling tree search problems.
The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
I think the signature should be:
// The path contains only 0s and 1s. 0 means go left and 1 means go right.
public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
// the class Node only has two fields:
Node{
Node left;
Node right;
I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
Anyone wants to help?Hi, JosAh,
That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
So I changed your code to be:
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
return search(root.right, node, path);
}I simply tested it with
Stack<Integer> path = new Stack<Integer>();
System.out.println( root, root.right.right, path);
root is the root of a complete binary tree with 7 nodes(4 leaves).
Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
Considerring , the right branch never pops, I changed it into
Then I changed it to :
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right ) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
if (search(root.right, node, path) != null) return path;
path.pop();
return path;
With the same test case, it returns [].
I will keep working on it.
Cheers,
Message was edited by:
since81
Message was edited by:
since81 -
i have this assignment for school. The first thing it says is: Write a binary tree class named my_Tree as the basic data structure. What does this mean? Can anyone give me an example of the java code that this should be written in?
Also, i have to sort a sequence of numbers in increasing order. I have the command line prompt written already, but how do i sort it using if/else statements? Thanks a lot. I'm really bad at java programming.i dont really understand that? Im really slow at
this. Can you clarify?Sorry. Here is a more complete implementation of a node.
// header file for class Node
// copywrong filestream. no rights reserved
#ifndef _NODE_H_
#define _NODE_H_
class Node
public:
Node();
Node(int x);
Type getinfo();
Node *getleft();
Node *getright();
void setinfo(Type x);
void setleft(Node *n);
void setright(Node *n);
private:
int info;
Node *left;
Node *right;
#endif -
How to serialize a binary tree object
HI Friends,
This is the problem.............................
I got a binary Tree Program with root (object ) containing the elements in the tree.
I got a server which performs insertions and deletions in the root.
Once it has got the operations right it has to send this object to client and Client will perform the search over this Binary Tree.
How to do this................................ Any Idea
Anyone can get me the Code....... It will be great to u....
reply me in this Id : [email protected]Have you looked at the TreeSet code.
This is a collection which stores data as a binary tree. It is serializable, has a look at the readObject and writeObject methods. -
How do we know if it's a leaf in a binary tree
how do we know if a node is a leaf in a binary tree?
Both the left and right nodes should be null.
-
How to extend breadth first Search for Binary Tree to any kind of Tree??
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
I have following code to successfully apply for breadth first Search in Binary Tree as follows,
package a.border;
import java.util.ArrayList;
import java.util.LinkedList;
public class Tree
int root;
Tree left;
Tree right;
static ArrayList<Integer> list = new ArrayList<Integer>();
static ArrayList<Tree> treeList = new ArrayList<Tree>();
private static LinkedList<Tree> queue = new LinkedList<Tree>();
* @param root root value
* @param left left node
* @param right right node
public Tree(int root, Tree left, Tree right)
this.root = root;
this.left = left;
this.right = right;
/** Creates a new instance of Tree
* You really should know what this does...
* @param root
public Tree(int root)
this.root = root;
this.left = null;
this.right = null;
* Simply runs a basic left then right traversal.
public void basicTraversal()
//Check if we can go left
if (left != null)
left.basicTraversal();
//Add the root
list.add(root);
//Check if we can go right
if (right != null)
right.basicTraversal();
public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
//Add the root to the arraylist, we know it is always the first entry.
list.add(root);
//Basically we add the first set of nodes into the queue for
//traversing.
//Query if left exists
if (left != null)
//Then add the node into the tree for traversing later
queue.add(left);
//Same for right
if (right != null)
queue.add(right);
//Then we call the traverse method to do the rest of the work
return traverse(list);
private ArrayList<Integer> traverse(ArrayList<Integer> list)
//Keep traversing until we run out of people
while (!queue.isEmpty())
Tree p = queue.remove();
//Check if it has any subnodes
if (p.left != null)
//Add the subnode to the back of the queue
queue.add(p.left);
//Same for left
if (p.right != null)
//Same here, no queue jumping!
queue.add(p.right);
//Append to the ArrayList
list.add(p.root);
//And return
return list;
* Makes a tree and runs some operations
* @param args
public static void main(String[] args)
* 4
* t = 2 6
* 1 3 5 7
Tree leaf6 = new Tree(1);
Tree leaf7 = new Tree(3);
Tree leaf8 = new Tree(5);
Tree leaf9 = new Tree(7);
Tree t4 = new Tree(2, leaf6, leaf7);
Tree t5 = new Tree(6, leaf8, leaf9);
Tree t = new Tree(4, t4, t5);
t.basicTraversal();
System.out.println("Here is basicTraversal ="+list.toString());
list.clear();
t.getBreadthTraversal(list);
System.out.println("getBreadthTraversal= " +list.toString());
list.clear();
}Can Guru help how to update to any kind of tree??
here this code is for the tree like:
* 4
* t = 2 6
* 1 3 5 7
*/But i hope the new code can handle tree like:
* 4
* / | \
* / | \
* t = 2 8 6
* / | \ | /| \
* 1 11 3 9 5 10 7
*/Thankssunnymanman wrote:
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
What do all trees have in common? And what do all nodes in trees have in common?
At least these things:
interface Tree<T> {
Node<T> getRoot();
interface Node<T> {
T getData();
List<Node<T>> getChildren();
}Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
class BinaryTree<T extends Comparable<T>> implements Tree<T> {
protected BTNode<T> root;
public Node<T> getRoot() {
return root;
class BTNode<T> implements Node<T> {
private T data;
private Node<T> left, right;
public List<Node<T>> getChildren() {
List<Node<T>> children = new ArrayList<Node<T>>();
children.add(left);
children.add(right);
return children;
public T getData() {
return data;
class NTree<T> implements Tree<T> {
private NTNode<T> root;
public Node<T> getRoot() {
return root;
class NTNode<T> implements Node<T> {
private T data;
private List<Node<T>> children;
public List<Node<T>> getChildren() {
return children;
public T getData() {
return data;
}Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
interface Traverser<T> {
List<Node<T>> traverse(T goal, Tree<T> tree);
}And finally write an implementation for it:
class BreathFirst<T> implements Traverser<T> {
public List<Node<T>> traverse(T goal, Tree<T> tree) {
Node<T> start = tree.getRoot();
List<Node<T>> children = start.getChildren();
// your algorithm here
return null; // return your traversal
}... which can be used to traverse any tree! Here's a small demo of how to use it:
public class Test {
public static void main(String[] args) {
Tree<Integer> binTree = new BinaryTree<Integer>();
// populate your binTree
Tree<Integer> nTree = new NTree<Integer>();
// populate your nTree
Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
// Look for integer 6 in binTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
// Look for integer 6 in nTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
}Good luck! -
A Binary Tree Implementation in ABAP
Hi,
Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
Thanks,
Manjula.Hi manjula,
This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It.
It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing through the tree.
For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
*& Report YBINTREE - Build/Print Binary Tree of numbers *
report ybintree .
types: begin of stree,
value type i,
left type ref to data,
right type ref to data,
end of stree.
data: tree type stree.
data: int type i.
data: begin of rnd occurs 0,
num type i,
end of rnd.
start-of-selection.
do 100 times.
generate random number between 0 and 100
call function 'RANDOM_I4'
exporting
rnd_min = 0
rnd_max = 100
importing
rnd_value = int.
store numbers
rnd-num = int.
append rnd.
build binary tree of random numbers
perform add_value using tree int.
enddo.
stored numbers are sorted for comparison
sort rnd by num.
print sorted random numbers
write: / 'Sorted Numbers'.
write: / '=============='.
skip.
loop at rnd.
write: rnd-num.
endloop.
skip.
print binary tree. This should give the same result
as the one listed from the internal table
write: / 'Binary Tree List'.
write: / '================'.
skip.
perform print_value using tree.
skip.
*& Form add_value
text - Build tree with value provided
-->TREE text
-->VAL text
form add_value using tree type stree val type i.
field-symbols: <ltree> type any.
data: work type stree.
if tree is initial. "When node has no values
tree-value = val. " assign value
clear: tree-left, tree-right.
create data tree-left type stree. "Create an empty node for left
create data tree-right type stree. "create an empty node for right
else.
if val le tree-value. "if number is less than or equal
assign tree-left->* to <ltree>. "assign the left node to fs
call add_value recursively with left node
perform add_value using <ltree> val.
else. "if number is greater
assign tree-right->* to <ltree>. "assign the right node to fs
call add_value recursively with right node
perform add_value using <ltree> val.
endif.
endif.
endform. "add_value
*& Form print_value
text - traverse tree from left-mid-right order
automatically this will be sorted list
-->TREE text
form print_value using tree type stree.
field-symbols: <ltree> type any.
if tree is initial. "node is empty
else. "non-empty node
assign tree-left->* to <ltree>. "left node
perform print_value using <ltree>. "print left
write: tree-value. "print the current value
assign tree-right->* to <ltree>. "right node
perform print_value using <ltree>. "print right
endif.
endform. "print_value
pls reward if helps,
regards.
Maybe you are looking for
-
Dump 'DYNPRO_SEND_IN_BACKGROUND'
Hi Guys, I am getting this dump everyday in my system. Please help me. Dump details: Screen output without connection to user. What happened? Error in ABAP application program. The current ABAP program "SAPLSLST " had to be terminated because one of
-
How do I get a voice memo to my computer?
I need to get the recorded into my MacBook Pro. Lion, 10.7.5. Can't send email, too long. Need this in my computer today. Thanks
-
Safari 6.0.5 crashing on startup
On loading up safari, I immediately get the wheel of doom and have an functionless application. Web pages do not load and have to force quit the application. Any suggestions as to how to fix this problem?
-
Ios 8 photos won't upload in safari to facebook status update
Installed iOS 8. I use Safari to access Facebook.com. photos will no longer upload to Facebook status update.
-
Authenticate with ntlm (or kerberos) using java UrlConnection
I need to consume a rest web service with java, passing the credentials of a domain user account. right now I'm doing it with classic asp set xmlHttp = server.createObject( "msxml2.serverxmlhttp" ) xmlHttp.open method, url, false, domain & "\" & user