Writting Methods of Binary Tree
I am using java code to write some binary tree methods.
Got stuck in some of the following methods.
Hopefully i can get some help here.
Public int width(){
// Return the maximun number of nodes in each level
Public boolean checkIsFullTree(){
// Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full)
Public boolean checkIsCompleteTree(){
// Return true if the tree is a full tree (If all leaves are at the same depth then the tree is full and is filled from left to right)
at last
Public int internalPathLength(){
// Return The sum of all internal nodes of the paths from the root of an extended binary tree to each node.
other words, the sum of all depths of nodes.
Looking forawad to see some replies. Chrees
I have came up with some ideas.
Public boolean checkIsFullTree(TreeNode t, int currentHeight ) {
int maxHeight = height(); // Maximum height.
int currentHeight=currentHeight;
if (t == null){
return false;
if (t.left() ! = null){
currentHeight++;
checkIsFullTree(t.left(), currentHeight);
if (t.right() ! = null){
currentHeight++;
checkIsFullTree(t.right(), currentHeight);
if ( t.left() == null && t.right() == null){
if (currentHeight == maxHeight) {
check = true;
}else{
check = false;
But i am missing sometime here i guess.
}
Similar Messages
-
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 -
Creating Insert Method for a binary tree
I have code for a binary tree http://sourcepost.sytes.net/sourceview.aspx?source_id=5046
I'm trying to create an insert method that will accept an element and insert it into my binary tree. The main purpose of this is to test my traversal functions, intrav(), postrav(), pretrav(). I have another class that will create 10 random numbers and call insert() to insert them into my tree. Can anyone help me write this method?anyone?
-
i have got a binary tree and i need to write a method which can count the number of leaves.
i have written the code as
static int countLeaves(BinaryNode node) {
if (node == null) {
return 0;
else if (node.left == null && node.right == null) {
return 1;
return countLeaves(node.left) + countLeaves(node.right);
}but, how can i put the method in the main funcion, i have tried
int leafCount = countLeaves(root);it gives an error message "non-static variable root cannot be referenced from a static context". How can i solve this problem? Thank you.the code looks like:
public class BinaryTree<AnyType>
public BinaryTree( )
root = null;
public BinaryTree( AnyType rootItem )
root = new BinaryNode<AnyType>( rootItem, null, null );
public void printPreOrder( )
if( root != null )
root.printPreOrder( );
public void printInOrder( )
if( root != null )
root.printInOrder( );
public void printPostOrder( )
if( root != null )
root.printPostOrder( );
public void makeEmpty( )
root = null;
public boolean isEmpty( )
return root == null;
public void merge( AnyType rootItem, BinaryTree<AnyType> t1, BinaryTree<AnyType> t2 )
if( t1.root == t2.root && t1.root != null )
System.err.println( "leftTree==rightTree; merge aborted" );
return;
if( this != t1 )
t1.root = null;
if( this != t2 )
t2.root = null;
public BinaryNode<AnyType> getRoot( )
return root;
private BinaryNode<AnyType> root;
static int countLeaves(BinaryNode node) {
if (node == null) {
return 0;
else if (node.left == null && node.right == null) {
return 1;
return countLeaves(node.left) + countLeaves(node.right);
static public void main( String [ ] args )
BinaryTree<Integer> t1 = new BinaryTree<Integer>( 1 );
BinaryTree<Integer> t3 = new BinaryTree<Integer>( 3 );
BinaryTree<Integer> t5 = new BinaryTree<Integer>( 5 );
BinaryTree<Integer> t7 = new BinaryTree<Integer>( 7 );
BinaryTree<Integer> t2 = new BinaryTree<Integer>( );
BinaryTree<Integer> t4 = new BinaryTree<Integer>( );
BinaryTree<Integer> t6 = new BinaryTree<Integer>( );
t2.merge( 2, t1, t3 );
t6.merge( 6, t5, t7 );
t4.merge( 4, t2, t6 );
// i want to run the method countLeaves here
int leafCount = countLeaves(root);
System.out.println("Number of leaves: "+leafCount);
} -
Binary tree inorder traversal without recursion
Using Java, write a method that does an in-order traversal of a binary tree WITHOUT using recursion. based on the following code
BTreeNode.java
public class BTreeNode
public BTreeNode LEFT;
public BTreeNode RIGHT;
public String VALUE;
BTreeUtil.java
public class BTreeUtil
public static void listNodes(BTreeNode a_oRootNode)
// insert code here...
}This is definitely the wrong place to post this. Nevertheless you'll have to use a stack. While traversing down the tree you push the parents onto the stack.
stephan -
Getting the height of a binary tree
So I am trying to create a method in my binary tree class that returns and integer that represents the height of the tree.
I tried to do this recursively and it seems the numbers are close to the actual ones, but never exact and I haven't really been able to find out where the problem lies. This is my code:
public int getHeight()
int height;
height = getHeightRecur(root);
return height;
public int getHeightRecur(BinTreeNode node)
int theight;
if(node == null)
theight = 0;
else
theight = 1 + getMax(getHeightRecur(node.leftN), getHeightRecur(node.rightN));
return theight;
private int getMax(int x, int y)
int result = 0;
if(x>y)
result = x;
if(y>x)
result = y;
return result;
}j2ee_ubuntu wrote:
it may help at some extent..
private int getMax(int x, int y)
int result = 0;
if(x>y)
result = x;
else if(y>x)
result = y;
else //when both are equal
result =x; OR result = y;//You can use one of them
return result;
}Edited by: j2ee_ubuntu on Nov 6, 2008 12:30 AMWhy not just use [ Math.max|http://java.sun.com/javase/6/docs/api/java/lang/Math.html#max(int,%20int)] or write
public static int max(int a, int b) {
return (a >= b) ? a : b;
} -
So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
I am sorry for such sloppy code.. I have been changing and rearranging too much.
import java.io.*;
import java.util.*;
public class MorseCode extends BinaryTree{
static BufferedReader in;
static BinaryTree<String> bT = new BinaryTree<String>();
/* public static void loadTree() throws FileNotFoundException, IOException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
public static String decode(Character c) throws IOException{
if(c.equals("null")){
return "";
}else if(c.equals(" ")){
return " ";
}else{
return (":" + find(c));
public static String find(Character c) throws IOException, FileNotFoundException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
Queue<BinaryTree> data = new LinkedList<BinaryTree>();
BinaryTree<String> tempTree = bT;
String temp = null;
Character tempChar = null;
data.offer(tempTree);
while(!data.isEmpty()){
tempTree = data.poll();
temp = tempTree.getData();
tempChar = temp.charAt(0);
if(tempChar.equals(c)){
break;
data.offer(tempTree.getRightSubtree());
data.offer(tempTree.getLeftSubtree());
return temp.substring(2);
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner scan = new Scanner(new FileReader("encode.in.txt"));
String s = "";
String temp = "";
while(scan.hasNextLine()){
temp = scan.nextLine();
for(int i = 0; i < temp.length(); i++){
s = s + decode(temp.charAt(i));
System.out.println(s);
/** Class for a binary tree that stores type E objects.
* @author Koffman and Wolfgang
class BinaryTree <E> implements Serializable
//===================================================
/** Class to encapsulate a tree node. */
protected static class Node <E> implements Serializable
// Data Fields
/** The information stored in this node. */
protected E data;
/** Reference to the left child. */
protected Node <E> left;
/** Reference to the right child. */
protected Node <E> right;
// Constructors
/** Construct a node with given data and no children.
@param data The data to store in this node
public Node(E data) {
this.data = data;
left = null;
right = null;
// Methods
/** Return a string representation of the node.
@return A string representation of the data fields
public String toString() {
return data.toString();
}//end inner class Node
//===================================================
// Data Field
/** The root of the binary tree */
protected Node <E> root;
public BinaryTree()
root = null;
protected BinaryTree(Node <E> root)
this.root = root;
/** Constructs a new binary tree with data in its root,leftTree
as its left subtree and rightTree as its right subtree.
public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
root = new Node <E> (data);
if (leftTree != null) {
root.left = leftTree.root;
else {
root.left = null;
if (rightTree != null) {
root.right = rightTree.root;
else {
root.right = null;
/** Return the left subtree.
@return The left subtree or null if either the root or
the left subtree is null
public BinaryTree <E> getLeftSubtree() {
if (root != null && root.left != null) {
return new BinaryTree <E> (root.left);
else {
return null;
/** Return the right sub-tree
@return the right sub-tree or
null if either the root or the
right subtree is null.
public BinaryTree<E> getRightSubtree() {
if (root != null && root.right != null) {
return new BinaryTree<E>(root.right);
} else {
return null;
public String getData(){
if(root.data == null){
return "null";
}else{
return (String) root.data;
/** Determine whether this tree is a leaf.
@return true if the root has no children
public boolean isLeaf() {
return (root.left == null && root.right == null);
public String toString() {
StringBuilder sb = new StringBuilder();
preOrderTraverse(root, 1, sb);
return sb.toString();
/** Perform a preorder traversal.
@param node The local root
@param depth The depth
@param sb The string buffer to save the output
private void preOrderTraverse(Node <E> node, int depth,
StringBuilder sb) {
for (int i = 1; i < depth; i++) {
sb.append(" ");
if (node == null) {
sb.append("null\n");
else {
sb.append(node.toString());
sb.append("\n");
preOrderTraverse(node.left, depth + 1, sb);
preOrderTraverse(node.right, depth + 1, sb);
/** Method to read a binary tree.
pre: The input consists of a preorder traversal
of the binary tree. The line "null" indicates a null tree.
@param bR The input file
@return The binary tree
@throws IOException If there is an input error
public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
// Read a line and trim leading and trailing spaces.
String data = bR.readLine().trim();
if (data.equals("null")) {
return null;
else {
BinaryTree < String > leftTree = readBinaryTree(bR);
BinaryTree < String > rightTree = readBinaryTree(bR);
return new BinaryTree < String > (data, leftTree, rightTree);
}//readBinaryTree()
/*Method to determine the height of a binary tree
pre: The line "null" indicates a null tree.
@param T The binary tree
@return The height as integer
public static int height(BinaryTree T){
if(T == null){
return 0;
}else{
return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
public static String preOrderTraversal(BinaryTree<String> T){
String s = T.toString();
String s2 = "";
String temp = "";
Scanner scan = new Scanner(s);
while(scan.hasNextLine()){
temp = scan.nextLine().trim();
if(temp.equals("null")){
s2 = s2;
}else{
s2 = s2 + " " + temp;
return s2;
}//class BinaryTreeAs well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
public static void main(String[] args) throws FileNotFoundException, IOException{
//Scanner scan = new Scanner(new FileReader("encode.in.txt"));
Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
public static String decode(Character c) throws IOException{
if(c.equals("null")){
c is a Character so it will never be the case that it is equal to the string n-u-l-l.
Perhaps the behaviour of each of these methods needs to be (documented and) tested. -
This is my first post here, forgive me if I've done something inappropiate :D
As the title says, it's about binary trees. To be exact, I have to sum up the values of all the nodes. So, using a recursive method seems apparent;
BIG FAT EDIT
Update: I got it working...I think. At least, it doesn't give any errors. But (!), the output isn't right. Here's the entire code (the eval methods in every class are the ones that might've been messed up, the rest should be fine):
public class TestVeelterm{
public static void main(String [] args){
Veelterm v = new Veelterm();
System.out.println("de veelterm is: " + v);
System.out.println("de waarde voor 2 is: " + v.eval(2));
System.out.println();
Term t;
t = new Term (-2,5);
v.add(t);
System.out.println("de veelterm is: " + v);
System.out.println("de waarde voor 1 is: " + v.eval(1));
System.out.println();
t = new Term (3,3);
v.add(t);
System.out.println("de veelterm is: " + v);
System.out.println("de waarde voor 2 is: " + v.eval(2));
System.out.println();
t = new Term (1,3);
v.add(t);
System.out.println("de veelterm is: " + v);
System.out.println("de waarde voor -3 is: " + v.eval(-3));
System.out.println();
t = new Term (2,5);
v.add(t);
System.out.println("de veelterm is: " + v);
System.out.println("de waarde voor 4 is: " + v.eval(4));
System.out.println();
class Veelterm{
private TermNode root;
public void add(Term term){
if (root == null)
root = new TermNode(term);
else
root.add(term);
public String toString(){
if (root == null)
return "0";
else
return root.toString();
public int eval(int x){
if (root == null)
return 0;
else
return root.eval(x);
class TermNode{
private TermNode left, right;
private Term content;
public TermNode(TermNode l, TermNode r, Term t){
left = l;
right = r;
content = t;
public TermNode (Term t){
this(null, null, t);
public String toString(){
String antwoord = "";
if (left != null)
antwoord += left.toString() + " ";
if (content.getCoefficient() >= 0)
antwoord += "+";
antwoord += content.toString();
if (right != null)
antwoord += " " + right.toString();
return antwoord;
public void add(Term t){
int myexp = content.getExponent();
int termexp = t.getExponent();
if (myexp == termexp){
int sum = t.getCoefficient() + content.getCoefficient();
content = new Term(sum, myexp);
else if (termexp < myexp){
if (left == null)
left = new TermNode(t);
else
left.add(t);
else{
if (right == null)
right = new TermNode(t);
else
right.add(t);
public int eval(int x){
// int sum = t.getCoefficient() + content.getCoefficient()
int z = 0;
int y = 0;
int p = 0;
if (left == null && right == null)
p = content.getCoefficient();
return p + z + y;
else
while (left != null && right != null){
z = z + content.getCoefficient();
y = y + content.getCoefficient();
if (left != null && right == null){
z = z + content.getCoefficient();
if (right != null && left == null){
y = content.getCoefficient();
return z + y;
class Term{
private int coefficient;
private int exponent;
public Term(int coeff, int exp){
coefficient = coeff;
exponent = exp;
public int getCoefficient(){
return coefficient;
public int getExponent(){
return exponent;
public String toString(){
return coefficient + "*X^" + exponent;
public int eval(int x){
int i;
i = 1;
while(i < exponent){
x = x * x;
i++;
return x * coefficient;
Now, as you've noticed already, I'm quite a newbie at java. As with this program, I can write it in pseudocode, but java is a pain. Or at least, I think so. Anyway, to cut to the case; the problem is: how do I add up the value of the nodes when they're not null?
No compiling errors.
Output =
de veelterm is: 0
de waarde voor 2 is: 0 (answer when x =2)
de veelterm is: -2*X^5
de waarde voor 1 is: -2 (answer when x =1)
de veelterm is: +3*x^2 - 2*X^5
de waarde voor 2 is: -2 (answer when x = 2)
etc
But it should be:
de veelterm is +3*X^2 - 2*X^5
de waarde voor 2 is: -40 (answer when x = 2)
Just ignore the dutch parts cough
I've been trying to figure out where I went wrong, and it's probably in the eval method in TermNode, but I can't seem to get it right...
Thanks in advance.
Message was edited by: Anzen...Once a - freaking - gain, sorry :p
Anzen
nullclass TermNode {
private TermNode left, right;
private Term content;
public TermNode(TermNode l, TermNode r, Term t) {
left = l;
right = r;
content = t;
public TermNode(Term t) {
this(null, null, t);
public String toString() {
String s = (left == null) ? "" : left.toString() + " + ";
s += content.toString();
s += (right == null) ? "" : " + " + right.toString();
return s;
public void add(Term t) {
int myexp = content.getExponent();
int termexp = t.getExponent();
if (myexp == termexp) {
int sum = t.getCoefficient() + content.getCoefficient();
content = new Term(sum, myexp);
} else if (termexp < myexp) {
if (left == null)
left = new TermNode(t);
else
left.add(t);
} else {
if (right == null)
right = new TermNode(t);
else
right.add(t);
public int eval(int x) {
int total = content.eval(x);
if(left != null)
total += left.eval(x);
if(right != null)
total += right.eval(x);
return total;
class Term {
private int coefficient;
private int exponent;
public Term(int coeff, int exp) {
coefficient = coeff;
exponent = exp;
public int getCoefficient() {
return coefficient;
public int getExponent() {
return exponent;
public String toString() {
boolean skip = coefficient == 1;
String s = skip ? "" : String.valueOf(coefficient) + "*";
return s + "x^" + exponent;
public int eval(int x) {
if(x == 0)
return x;
int i = 0;
int product = 1;
while(i++ < exponent)
product *= x;
return product * coefficient;
} -
So this is my first post here and i am beginning to like this forum.
Can anybody help me on how to construct Binary tree from inorder and postorder traversals,i just want to know the algorithm so that i can apply it.
Please help.I would like to pick a minor little nit with this analysis. The algorithm that has been proposed assumes that all the nodes are all distinct and that having selected the root from the end of the post-order listing that it is POSSIBLE to find it in the in-order list. What if you find multiple copies of this node?
If multiple copies of the root are found, you must have a method to distinguish, which one is the proper dividing point. In the worst possible case, the problem can not be solved at all. For example suppose my post-order and my in-order lists were these:
a a a a a
a a a a a
The shape of the tree is indeterminant in this case.
If you allow different tree nodes to contain identical values your recursive algorithm needs some modification.
The fix is this:
1) allow your recursive algorithm to fail (and report back any success or failure)
This can and happen if the two lists that you passed in are incompatible. For example they could have different nodes in them.
2) when you pick the root off the end of the post order list, you search for it in the in-order list, you could find multiple matches or you could find no matches. You must explore each of these independently because each one could lead to a possible different solution, or could lead to no solution. Of course in the case of no matches, you must report back a failure.
Depending on your needs, you can either stop the first time that you have successfully assembled a tree that matches the two supplied inputs, or you can have it grind on and have it enumerate all the possible tree arrangements that could have generated from the two traversals that you started with.
It might help to visualize if you write out all the possible trees with just the three nodes AAB. There are 15 of them, 5 with B at the root, 5 with A at the root and B in the left and 5 with B in the right. It is easy to draw the trees and to immediately write both their in-order and their post-order traversals.
Any traversal is just a list of the 3 nodes and there are 3 arrangements, AAB, ABA, and BAA. There are exactly 9 ordered pairs of these traversals so you can't get all 15 trees from the 9 pairs.
Sho nuff, three ordered pairs are unambiguous and generate a single unique tree(e.g. in:BAA post:ABA) and six of them come from ambiguous pairs of trees (e.g. in:ABA post:ABA - you can't tell if this is a tree ABA all leaning to the left or all leaning to the right)
Enjoy -
I must make a method that takes the variable "item" and put it in a string, for each element of the binary tree, but per levels..for example:
1
2 3 6
5 4must return this string: 1 , 2 , 3 , 6 , 5 , 4
The tree is something like:
public class BinTree{
private Node root;
public class Node{
public Node left;
public Node right;
public int item;
}Thank you very much :)Sorry, I didn't specify: I can use recursion,Level order traversals are normally performed using a queue.
but in this case I don't know how to do it "per levels"..can
someone help me? Sure: use a queue and try to do it first on a pice of paper.
Also if you don't write the method,I won't. ; )
What would you learn from that? Perhaps a little, but you'll learn far more by doing it yourself.
just to tell me how to go through the tree in this
case. ThanksHere's some pseudo code:
LEVELORDER(root)
queue.enqueue(root)
WHILE queue not empty
n = queue.dequeue()
IF n.left != null -> queue.enqueue(n.left )
IF n.right != null -> queue.enqueue(n.right)
END WHILE
END LEVELORDERAnd an example. Take the following tree: 5
3 8
1 4 6 9No apply that pseudo code:
queue = new queue
queue.enqueue(5)
while(queue is not empty) {
n = queue.dequeue() = 5
n.left != null, so queue.enqueue(3)
n.irght != null, so queue.enqueue(8)
(queue is now [3,8])
n = queue.dequeue() = 3
n.left != null, so queue.enqueue(1)
n.irght != null, so queue.enqueue(4)
(queue is now [8,1,4])
n = queue.dequeue() = 8
n.left != null, so queue.enqueue(6)
n.irght != null, so queue.enqueue(9)
(queue is now [1,4,6,9])
n = queue.dequeue() = 1
n.left == null
n.irght == null
(queue is now [4,6,9])
n = queue.dequeue() = 4
n.left == null
n.irght == null
(queue is now [6,9])
n = queue.dequeue() = 6
n.left == null
n.irght == null
(queue is now [9])
n = queue.dequeue() = 9
n.left == null
n.irght == null
(queue is now [])
queue is empty, end while.
}As you can see, the items are dequeued in the following order: 5, 3, 8, 1, 4, 6, 9.
Good luck. -
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! -
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 -
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. -
I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
Tree B has a similar structure.
The node used for both A and B.
Node{
Node left;
Node right;
My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
So, the method should look like:
public Node search(Node rootOfA, Node rootOfB){
I know a simple recursive fuction can do the job. The question is all about the effciency....
I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
Anyone knows of that? Any friend can give a sound solution?
Thank you all in advance.
Jason
Message was edited by:
since81I'm not too sure if this would help but there goes.
I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.
:) -
Ok, I am making a binary tree. I have a question for my insert method. Firstly, I can't find out why the root node is inserted more than once in the tree. Also, I am having trouble with connecting the nodes that I insert to the tree. I can attach modes to root just fine, but I can't find out how to attach nodes to the existing nodes that are already attached to the tree. When I insert a node that meets the criteria of an already existing node, it replaces the node instead of getting attached to it. The answer is probably trivial, but I can't find it. Here is my insert method.
public void insert(T obj) {
int _result1;
int _result2;
//TODO: Implement Q1 here
if(isEmpty() == true){
_root = createNode(obj, null, null, null);
System.out.println("The root inserted is " + _root.element());
insert(obj);
_node = createNode(obj, _root, null, null);
_result1 = _node.element().compareTo(_root.element());
if(_result1 < 0){
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _node2.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " + _current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasLeft() == true){
_node1.getLeft();
_current = _node1.getLeft();
else{
_current.setLeft(_node1);
_current = _node2;
else{
_node1 = createNode(obj, _node, null, null);
_node.setLeft(_node1);
_node1.setParent(_node);
System.out.println("The parent of the left node " + _node.element() + " is " + _node.getParent().element());
_root.setLeft(_node1);
_current = _node1;
//System.out.println("The current element is " + _node.element());
else{
if(_node.isInternal() == true){
_current = (BTreeNode<T>) _current.element();
_result2 = _current.element().compareTo(_current.getParent().element());
//System.out.println("The current element is " +_current.element());
if(_result2 < 0){
_node1.getLeft();
_current = _node1.getLeft();
else{
_node1.getRight();
_current = _node1.getRight();
if(_node1.hasRight() == true){
_node1.getRight();
_current = _node1.getRight();
else{
_current.setLeft(_node1);
_current = _node1;
else{
_node1 = createNode(obj, _node, null, null);
_node.setRight(_node1);
_node1.setParent(_node);
//_current = _node1;
System.out.println("The parent of the right node " + _node.element() + " is " + _node.getParent().element());
_root.setRight(_node1);
_current = _node1;
//System.out.println("The current element is " + _current.element());
}The output I get is:
The root inserted is 6
The parent of the right node 6 is 6
The parent of the right node 6 is 6 ** I can't figure out why the root is inserted two extra times**
The parent of the left node 3 is 6
The parent of the right node 11 is 6
The parent of the right node 12 is 6 ** this node should be attaching to 11 instead of replacing it **
The parent of the right node 8 is 6
The parent of the right node 9 is 6
The parent of the right node 10 is 6
The parent of the right node 7 is 6
preorder :(6 (3 )(7 ))
postorder:(( 3) ( 7) 6)IMO, your insert method is way too complicated.
Have a look at this pseudo code: that's all it takes to insert nodes in a BT:
class Tree<T extends Comparable<T>> {
private Node root;
public void insert(T obj) {
'newNode' <- a new Node('obj') instance
IF 'root' equals null
let 'root' be the 'newNode'
ELSE
insert('root', 'newNode')
END IF
public void insert(Node parent, Node newNode) {
IF 'parent' is less than 'newNode'
IF the left child of 'parent' is null
let 'newNode' be the left child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
ELSE
IF the right child of 'parent' is null
let 'newNode' be the right child of 'parent'
ELSE
make a recursive call here: insert('???', 'newNode')
END IF
END IF
}
Maybe you are looking for
-
Hi.. I have a problem with forgetting my answers for he questions ..what should I do please??????
-
Returns from vendor special stock O
Hi, all. Does anyone know, how can I make a returns from vendor, special stock O? Thanks in advance. HAL
-
No default gw, Proxy, NetworkManager, WiFi, browser works, terminal no
Hi everybody, i'm using Arch since some months and generally i'm able to solve all my problems on the wiki, but this time i cannot understand what's wrong... Well, i have internet through a proxy with auth, so i set up all the env var (http_proxy and
-
IOS 7 (7.1.2) Update disabled my wifi ***?? HELP
So I foolishly only have my backups in the iCloud I just did the update on my 4S and the wifi became disabled. So I restored my device to the latest version as there is no other choice. 7.1.2 screwed me. So even now my wifi is now disabled - so what
-
Popup parenting issues in multi window
Hello folks, I have a multi-window AIR application - there is one base application window, but we currently hide that and use mx:Window for all of our application windows. The application allows you to open new windows to enable easy drag and drop be