Binary Tree (insert level by level)
Hello,
I'm trying to program a binary tree. It's totally clear for me to insert new (Integer) Values in an ordinary binary tree.
I simply have to check if the root is equal (--> ready) smaller or larger than the value. I repeat this until I reached a leaf and then I insert a new node.
BUT:
My teacher gave me following problem: Inserting values level by level. The first element is the root, the leftson of the root is nuber2 the rightson of the root is number3
The leftson of root's leftson is number4, the rightson of root's leftson is number 5, the leftson of root's rightson is number 6 and so on.
I have NO idea how to program that.
For example: the 23rd element is in the tree: left, right, right, right, whilst the 24th element is right, left, left, left.
I cannot find a recursive structure, that solves the problem.
Perhaps YOU can save me from gettin' mad ;o)
I really hope so.
It's not quite clear what you mean by level-by-level (at least not to me). The structure of a binary tree depends in the insert order. If you insert 1,5,2,8 the tree will look different to when you insert 1,2,3,4. In the last case the tree actually has degenerated to a linked list (there are only rightsons).
Now, to minimize the number of levels (if that's what this is about) there's a technique called balancing. In a perfectly balanced binary tree each level is filled before a new level is started. This is quite complicated. Search the net or look in some data structures textbook for balanced binary trees.
Similar Messages
-
Binary tree (level by level insert)
Hello,
I already posted this artivle in the Forum "Java Programming" because I'm new to the Forum and didn't see the Algorithms part.. Sorry for the double posting.
I'm trying to program a binary tree. It's totally clear for me to insert new (Integer) Values in an ordinary binary tree.
I simply have to check if the root is equal (--> ready) smaller or larger than the value. I repeat this until I reached a leaf and then I insert a new node.
BUT:
My teacher gave me following problem: Inserting values level by level. The first element is the root, the leftson of the root is nuber2 the rightson of the root is number3
The leftson of root's leftson is number4, the rightson of root's leftson is number 5, the leftson of root's rightson is number 6 and so on.
I have NO idea how to program that.
For example: the 23rd element is in the tree: left, right, right, right, whilst the 24th element is right, left, left, left.
I cannot find a recursive structure, that solves the problem.
Perhaps YOU can save me from gettin' mad ;o)
I really hope so.But can you think of a recursive code to solve the problem????????Ok, here's another hint -- take that node 23 again as an example. If you write out this number in binary (10111) and skip the leftmost 1 in this pattern (x0111), start reading from left to right, starting at the right of th 'x'. 0 denotes left, 1 denotes right. Does that ring a bell?
Something like the following (pseudo code) should come up --
insert(Node node, int val, int pattern, int bitmask) {
if (bitmask == 1) // we have to insert now
if ((pattern & bitmask) == 1) // insert right
node.right= new Node(val);
else // insert left
node.left= new Node(val);
else if ((pattern & bitmask) == 1) // move right
insert(Node.right, val, pattern, bitmask >> 1);
else // move left
insert(Node.left, val, pattern, bitmask >> 1);
}Some bits and pieces are left as an exercise ;-)
kind regards,
Jos -
Binary Tree: Number of Nodes at a Particular Level
Hi, I'm trying to teach myself about binary tree but am having trouble writing an algorithm. The algorithm that I'm trying to write is one that will take a binary tree and output the number of nodes at each level of the tree (maybe in an array).
I have no trouble writing an algorithm that does a breadth-first traversal, but I have lots of trouble trying to determine where each level ends.
Thanks for the helpTry something like this:
class BTree {
BTreeNode root;
public int numberOfNodesAtLevel(int level) {
if(root == null) return -1;
return numberOfNodesAtLevel(root, level);
private int numberOfNodesAtLevel(BTreeNode node, int level) {
if(level == 0) {
return 1;
} else {
return (node.left == null ? 0 : numberOfNodesAtLevel(node.left, level-1)) +
(node.right == null ? 0 : numberOfNodesAtLevel(node.right,level-1));
} -
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. -
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?
-
Implementing tree control in third level navigation
Hello
1. Is it possible to Implement a tree control inside third level navigation ?
2. How can I make selecting one of the nodes change the display in another iview on the same page ?
(How do they pass data to one another)
3. Is it possible to select several nodes at once ?
P.S
Is there a how to guid out there ?
Thanks
Ziv.Hi,
I undestand you want to hide/show tree nodes on demand.
in the standard DTN (detailed navigation) it isn't possible.
There are two options -
1. As suggested you can modify the DTN provided by SAP - all the code is under com.sap.portal.navigation.detailedtree.par and the iView name is also com.sap.portal.detailedNavigationTree
2. create this tree from scratch, and put it on the left side instead of the DTN or as a dynamic navigation iView.
For creating navigation iViews by yourself, you can start from here:
http://help.sap.com/saphelp_nw70/helpdata/EN/43/0174a642406db7e10000000a422035/frameset.htm
Regards,
Tal.
Edited by: Tal Haviv on Aug 15, 2008 12:55 PM -
How to traverse level by level in tree
Wondering if there were any suggestions on how to efficiently traverse through a tree level by level.
Here is my code for creating the tree.
public static void main(String[] args)
String userInput = "";
StringTokenizer tokenizedUserInput;
int numAdd = 0;
STree<Integer> completeTree = new STree<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter values for tree: ");
userInput = keyboard.nextLine();
tokenizedUserInput = new StringTokenizer(userInput, ", ");
while (tokenizedUserInput.hasMoreTokens())
numAdd = Integer.parseInt(tokenizedUserInput.nextToken());
completeTree.add(numAdd);
}I have found a method to traverse through the tree level by level but it takes in a parameter of a node. I'm
not sure how to take my tree and pass it through the method. Here is the method:
public static <T> String levelByLevel(TNode<T> t)
LinkedQueue<TNode<T>> q = new LinkedQueue<TNode<T>>();
TNode<T> p;
String s = "";
q.push(t);
while(!q.isEmpty())
p = q.pop();
s += p.nodeValue + " ";
if(p.left != null)
q.push(p.left);
if(p.right != null)
q.push(p.right);
return s;
} -
I have a project where I need to build a binary tree with random floats and count the comparisons made. The problem I'm having is I'm not sure where to place the comaprison count in my code. Here's where I have it:
public void insert(float idata)
Node newNode = new Node();
newNode.data = idata;
if(root==null)
root = newNode;
else
Node current = root;
Node parent;
while(true)
parent = current;
if(idata < current.data)
comp++;
current = current.leftc;
if(current == null)
parent.leftc = newNode;
return;
else
current = current.rightc;
if(current == null)
parent.rightc = newNode;
return;
}//end insertDo I have it in the right place? Also, if I'm building the tree for 10,000 numbers would I get a new count for each level or would I get one count for comparisons?? I'd appreciate anyone's help on this.You never reset the comp variable, so each timeyou
insert into the tree, it adds the number ofinserts
to the previous value.Yes, or something like that. I'm not sure what theOP
really means.Yeah, it's hard to be sure without seeing the rest of
the code.Sorry, I thought I had already posted my code for you to look at.
Here's a copy of it:
class Node
public float data;
public Node leftc;
public Node rightc;
public class Btree
private Node root;
private int comp;
public Btree(int value)
root = null;
public void insert(float idata)
Node newNode = new Node();
newNode.data = idata;
if(root==null)
root = newNode;
else
Node current = root;
Node parent;
while(true)
parent = current;
comp++;
if(idata < current.data)
current = current.leftc;
if(current == null)
parent.leftc = newNode;
return;
else
current = current.rightc;
if(current == null)
parent.rightc = newNode;
return;
}//end insert
public void display()
//System.out.print();
System.out.println("");
System.out.println(comp);
} //end Btree
class BtreeApp
public static void main(String[] args)
int value = 10000;
Btree theTree = new Btree(value);
for(int j=0; j<value; j++)
float n = (int) (java.lang.Math.random() *99);
theTree.insert(n);
theTree.display();
} -
CTE for Count the Binary Tree nodes
i have the table structure like this :
Create table #table(advId int identity(1,1),name nvarchar(100),Mode nvarchar(5),ReferId int )
insert into #table(name,Mode,ReferId)values('King','L',0)
insert into #table(name,Mode,ReferId)values('Fisher','L',1)
insert into #table(name,Mode,ReferId)values('Manasa','R',1)
insert into #table(name,Mode,ReferId)values('Deekshit','L',2)
insert into #table(name,Mode,ReferId)values('Sujai','R',2)
insert into #table(name,Mode,ReferId)values('Fedric','L',3)
insert into #table(name,Mode,ReferId)values('Bruce','R',3)
insert into #table(name,Mode,ReferId)values('paul','L',4)
insert into #table(name,Mode,ReferId)values('walker','R',4)
insert into #table(name,Mode,ReferId)values('Diesel','L',5)
insert into #table(name,Mode,ReferId)values('Jas','R',5)
insert into #table(name,Mode,ReferId)values('Edward','L',6)
insert into #table(name,Mode,ReferId)values('Lara','R',6)
select *from #table
How do i write the CTE for count the Binary tree nodes on level basis. Here is the example,
now,what i want to do is if i'm going to calculate the Count of the downline nodes.which means i want to calculate for '1' so the resultset which i'm expecting
count level mode
1 1 L
1 1 R
2 2 L
2 2 R
4 3 L
2 3 R
How do i acheive this,i have tried this
with cte (advId,ReferId,mode,Level)
as
select advId,ReferId,mode,0 as Level from #table where advid=1
union all
select a.advId,a.ReferId,a.mode ,Level+1 from #table as a inner join cte as b on b.advId=a.referId
select *From cte order by Level
i hope its clear. Thank youSee Itzik Ben-Gan examples for the subject
REATE TABLE Employees
empid int NOT NULL,
mgrid int NULL,
empname varchar(25) NOT NULL,
salary money NOT NULL,
CONSTRAINT PK_Employees PRIMARY KEY(empid),
CONSTRAINT FK_Employees_mgrid_empid
FOREIGN KEY(mgrid)
REFERENCES Employees(empid)
CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
SET NOCOUNT ON
INSERT INTO Employees VALUES(1 , NULL, 'Nancy' , $10000.00)
INSERT INTO Employees VALUES(2 , 1 , 'Andrew' , $5000.00)
INSERT INTO Employees VALUES(3 , 1 , 'Janet' , $5000.00)
INSERT INTO Employees VALUES(4 , 1 , 'Margaret', $5000.00)
INSERT INTO Employees VALUES(5 , 2 , 'Steven' , $2500.00)
INSERT INTO Employees VALUES(6 , 2 , 'Michael' , $2500.00)
INSERT INTO Employees VALUES(7 , 3 , 'Robert' , $2500.00)
INSERT INTO Employees VALUES(8 , 3 , 'Laura' , $2500.00)
INSERT INTO Employees VALUES(9 , 3 , 'Ann' , $2500.00)
INSERT INTO Employees VALUES(10, 4 , 'Ina' , $2500.00)
INSERT INTO Employees VALUES(11, 7 , 'David' , $2000.00)
INSERT INTO Employees VALUES(12, 7 , 'Ron' , $2000.00)
INSERT INTO Employees VALUES(13, 7 , 'Dan' , $2000.00)
INSERT INTO Employees VALUES(14, 11 , 'James' , $1500.00)
The first request is probably the most common one:
returning an employee (for example, Robert whose empid=7)
and his/her subordinates in all levels.
The following CTE provides a solution to this request:
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
-- Anchor Member (AM)
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 7
UNION ALL
-- Recursive Member (RM)
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees AS E
JOIN EmpCTE AS M
ON E.mgrid = M.empid
SELECT * FROM EmpCTE
Using this level counter you can limit the number of iterations
in the recursion. For example, the following CTE is used to return
all employees who are two levels below Janet:
WITH EmpCTEJanet(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 3
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTEJanet as M
ON E.mgrid = M.empid
WHERE lvl < 2
SELECT empid, empname
FROM EmpCTEJanet
WHERE lvl = 2
As mentioned earlier, CTEs can refer to
local variables that are defined within the same batch.
For example, to make the query more generic, you can use
variables instead of constants for employee ID and level:
DECLARE @empid AS INT, @lvl AS INT
SET @empid = 3 -- Janet
SET @lvl = 2 -- two levels
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = @empid
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTE as M
ON E.mgrid = M.empid
WHERE lvl < @lvl
SELECT empid, empname
FROM EmpCTE
WHERE lvl = @lvl
Results generated thus far might be returned (but are not guaranteed to be),
and error 530 is generated. You might think of using the MAXRECURSION option
to implement the request to return employees who are two levels below
Janet using the MAXRECURSION hint instead of the filter in the recursive member
WITH EmpCTE(empid, empname, mgrid, lvl)
AS
SELECT empid, empname, mgrid, 0
FROM Employees
WHERE empid = 1
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1
FROM Employees as E
JOIN EmpCTE as M
ON E.mgrid = M.empid
SELECT * FROM EmpCTE
OPTION (MAXRECURSION 2)
WITH EmpCTE(empid, empname, mgrid, lvl, sortcol)
AS
SELECT empid, empname, mgrid, 0,
CAST(empid AS VARBINARY(900))
FROM Employees
WHERE empid = 1
UNION ALL
SELECT E.empid, E.empname, E.mgrid, M.lvl+1,
CAST(sortcol + CAST(E.empid AS BINARY(4)) AS VARBINARY(900))
FROM Employees AS E
JOIN EmpCTE AS M
ON E.mgrid = M.empid
SELECT
REPLICATE(' | ', lvl)
+ '(' + (CAST(empid AS VARCHAR(10))) + ') '
+ empname AS empname
FROM EmpCTE
ORDER BY sortcol
(1) Nancy
| (2) Andrew
| | (5) Steven
| | (6) Michael
| (3) Janet
| | (7) Robert
| | | (11) David
| | | | (14) James
| | | (12) Ron
| | | (13) Dan
| | (8) Laura
| | (9) Ann
| (4) Margaret
| | (10) Ina
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Adding to a Linked Complete Binary Tree
Hi all,
I am having major trouble trying to grasp the concept behind adding to a Complete Binary Tree (linked structure). It is part of a much larger assignment that uses a Heap Priority Queue and I am genuinely stuck. I have noticed that there seems to be some sort of strike going on so I wont expect a reply to this.
I understand that Binary Tree's are useful because of their recursive nature, does the process of adding use recursion also. My mind is a mess at the moment so forgive the rambling. My problem exists when I go to add after a right child on a lower level(anything below level 3). I have come to the conclusion that I it is impossible to continue with my adding method and that I should scrap it. Can anyone point anything relevant out to me? I'd appreciate it, thank you.
public class LinkedBT implements CompleteBT
private BTNode root; //a reference to the root node
private BTNode current; //a reference to the last inserted node
private BTNode firstNodeInLevel; //a reference to the first node in the level
private int size; //keeps track of the size of the BT
private int currentLevel;
private int leafCount;
public LinkedBT()
root = null; //instantiate instance variables
current = null;
size = 0;
currentLevel = 0; //indicates that there are no nodes
leafCount = 0;
firstNodeInLevel = null;
public boolean isEmpty()
return (root==null);
public int size()
return size;
public void add(Object obj, int priority)
BTNode tempNode = new BTNode(obj, priority);
tempNode.parent = current; //set the parent of the node to current
if(isEmpty()) //if the tree is empty then make a new BTNode and give it the root reference
root = tempNode;
current = root; //make current reference to the root node
size++;
currentLevel++; //increments currentLevel
return; //return control to calling method
if(current.childrenFull!=true) //if the current node has available children positions then check left and right and add BTNode appropriately
if(current.leftChild==null)
if(leafCount==0) //if this is the first node to be added on any given level then.....
firstNodeInLevel = tempNode; //.....store a reference to it for future adding purposes
current.leftChild = tempNode; //adds BTNode to left child
leafCount++;
else
current.rightChild = tempNode; //add BTNode to right child
leafCount++;
current.childrenFull = true; //after adding the right child set the childrenFull property true NECESSARY?????
if(Math.pow(2, currentLevel)==leafCount) //IF THIS EVALS TO TRUE THEN THE MAX NUMBER OF LEAVES FOR THAT LEVEL IS REACHED
currentLevel++; //increment the level
leafCount = 0; //reset the leaf count
current = firstNodeInLevel; //change current to the furthest leaf on the left
else //ELSE NEED TO GO BACK UP AND FIND NEXT FEASIBLE POSITION
//while(current.parent.rightChild.leftChild.)----------------THIS DOESNT WORK WHEN THE TREE GETS BIGGER
//current = current.parent; //set current to next feasible position
size++;
public Object getRoot()
return root;
public void heapSort()
private class BTNode
private Object value;
private int key;
private BTNode parent;
private BTNode leftChild;
private BTNode rightChild;
private boolean childrenFull; //initially false, when both children are occupied then change to true
private BTNode(Object obj, int priority) //constructor accepts the value and the priority key
value = obj;
key = priority;
parent = null;
leftChild = null;
rightChild = null;
childrenFull = false;
public boolean hasNoChildren()
return(leftChild==null && rightChild==null); //returns true if the node has no children
}Currently working on setting the Linked Servers Security properties. Added the SQLAgent in the" Local server login to remote server login mappings:". The SQLAgent is the only entry in the grid. The SQLAgent has the Remote User and Remote Password
of the AS400. Then below have "Not be made" for "For a login not defined in the lst above, connections will:".
So provided that the SQL Admin only gives SQL Job create, Job Alter and Alter Linked Server to user/groups that he wants to use the linked server the Admin can control access to the linked server.
Any thoughts? -
Binary Tree in Java - ******URGENT********
HI,
i want to represent a binary tree in java. is there any way of doing that.
thanx
sraphsonHI,
i want to represent a binary tree in java. is there
e any way of doing that.
thanx
sraphsonFirst, what is a binary tree? Do you know how the binary tree looks like on puesdo code? How about a representation in terms of numbers? What is a tree? What is binary? The reason I ask is, what do you know about programming?
Asking to represent a binary tree in java seems like a question who doesn't know how it looks like in the first please. Believe me, I am one of them. I am not at this level yet. If you are taking a class that is teaching binary trees and you don't know how it looks like, go back to your notes.
Sounds harsh, but it is better to hear it from a person that doesn't know either then a boss that hired you because Computer Science was what you degree said. Yet, you don't know how to program?
Telling you will not help you learn. I can show you tutorials of trees would be start on where to learn.
HOW TO USE TREES (oops this is too simple, but it is a good example)
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
CS312 Data Structures and Analysis of Algorithms
(Here is a course about trees. Search and learn)
http://www.calstatela.edu/faculty/jmiller6/cs312-winter2003/index.htm -
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 PMThe 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 -
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. ChreesI 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.
} -
Need Help with a String Binary Tree
Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
plssss... someone pls help me on this
here is my code now:
// TreeApp.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*; // for I/O
import java.util.*; // for Stack class
import java.lang.Integer; // for parseInt()
class Node
//public int iData; // data item (key)
public String iData;
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
} // end class Node
class Tree
private Node root; // first node of tree
public Tree() // constructor
{ root = null; } // no nodes in tree yet
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
return current; // found it
} // end find()
public Node recfind(int key, Node cur)
if (cur == null) return null;
else if (key < cur.iData) return(recfind(key, cur.leftChild));
else if (key > cur.iData) return (recfind(key, cur.rightChild));
else return(cur);
public Node find2(int key)
return recfind(key, root);
public void insert(int id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public void insert(String id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
//if(id < current.iData) // go left?
if(id.compareTo(current.iData)>0)
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public Node betterinsert(int id, double dd)
// No duplicates allowed
Node return_val = null;
if(root==null) { // no node in root
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
root = newNode;
return_val = root;
else // root occupied
Node current = root; // start at root
Node parent;
while(current != null)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.leftChild = newNode;
} // end if go left
else if (id > current.iData) // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.rightChild = newNode;
} // end else go right
else current = null; // duplicate found
} // end while
} // end else not root
return return_val;
} // end insert()
public boolean delete(int key) // delete node with given key
if (root == null) return false;
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while(current.iData != key) // search for node
parent = current;
if(key < current.iData) // go left?
isLeftChild = true;
current = current.leftChild;
else // or go right?
isLeftChild = false;
current = current.rightChild;
if(current == null)
return false; // didn't find it
} // end while
// found node to delete
// if no children, simply delete it
if(current.leftChild==null &&
current.rightChild==null)
if(current == root) // if root,
root = null; // tree is empty
else if(isLeftChild)
parent.leftChild = null; // disconnect
else // from parent
parent.rightChild = null;
// if no right child, replace with left subtree
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
// if no left child, replace with right subtree
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;
else // two children, so replace with inorder successor
// get successor of node to delete (current)
Node successor = getSuccessor(current);
// connect parent of current to successor instead
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// connect successor to current's left child
successor.leftChild = current.leftChild;
// successor.rightChild = current.rightChild; done in getSucessor
} // end else two children
return true;
} // end delete()
// returns node with next-highest value after delNode
// goes to right child, then right child's left descendents
private Node getSuccessor(Node delNode)
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; // go to right child
while(current != null) // until no more
{ // left children,
successorParent = successor;
successor = current;
current = current.leftChild; // go to left child
// if successor not
if(successor != delNode.rightChild) // right child,
{ // make connections
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
return successor;
public void traverse(int traverseType)
switch(traverseType)
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
System.out.println();
private void preOrder(Node localRoot)
if(localRoot != null)
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
private void inOrder(Node localRoot)
if(localRoot != null)
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
private void postOrder(Node localRoot)
if(localRoot != null)
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
public void displayTree()
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
while(isRowEmpty==false)
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
Node temp = (Node)globalStack.pop();
if(temp != null)
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
else
System.out.print("--");
localStack.push(null);
localStack.push(null);
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
} // end displayTree()
} // end class Tree
class TreeApp
public static void main(String[] args) throws IOException
int value;
double val1;
String Line,Term;
BufferedReader input;
input = new BufferedReader (new FileReader ("one.txt"));
Tree theTree = new Tree();
val1=0.1;
while ((Line = input.readLine()) != null)
Term=Line;
//val1=Integer.parseInt{Term};
val1=val1+1;
//theTree.insert(Line, val1+0.1);
val1++;
System.out.println(Line);
System.out.println(val1);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
while(true)
putText("Enter first letter of ");
putText("show, insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
case 's':
theTree.displayTree();
break;
case 'i':
putText("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
putText("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
putText("Found: ");
found.displayNode();
putText("\n");
else
putText("Could not find " + value + '\n');
break;
case 'd':
putText("Enter value to delete: ");
value = getInt();
boolean didDelete = theTree.delete(value);
if(didDelete)
putText("Deleted " + value + '\n');
else
putText("Could not delete " + value + '\n');
break;
case 't':
putText("Enter type 1, 2 or 3: ");
value = getInt();
theTree.traverse(value);
break;
default:
putText("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static void putText(String s)
System.out.print(s);
System.out.flush();
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class TreeAppString str = "Hello";
int index = 0, len = 0;
len = str.length();
while(index < len) {
System.out.println(str.charAt(index));
index++;
} -
I'm writing a binary tree class and am having some trouble with the Insert function. Here is the code for the TreeNode class...
public class TreeNode
TreeNode Left;
TreeNode Right;
String Name;
public TreeNode(String NodeName)
Left = null;
Right = null;
Name = NodeName;
}And this is the code for the Tree class...
public class Tree
TreeNode Root;
public Tree(String RootNode)
Root = new TreeNode(RootNode);
public void Insert(String Name)
InsertNode(Root, Name);
public void InsertNode(TreeNode t, String NodeName)
if (t == null)
t = new TreeNode(NodeName);
else
if (NodeName.compareTo(t.Name) < 0)
InsertNode(t.Left, NodeName);
else if (NodeName.compareTo(t.Name) > 0)
InsertNode(t.Right, NodeName);
else if (NodeName.compareTo(t.Name) == 0)
System.out.println("Entered node that was already in Tree");
}When I enter a new node into a Tree containing just the root, it follows the recursion through once, then creates the new TreeNode as it should. However, the new node is not really recognized by the tree because when I try to insert another node, it only finds the root in the tree and only goes through one recursion. What's wrong?I believe t.Left (or t.Right) is getting set in the line
t = new TreeNode(NodeName);
Since it is a recursive function, when it is called the second time, the "t" that is passed in is actually the original t.left (I think), which is getting set then.
Maybe you are looking for
-
Adobe Bridge overrides Windows Explorer functions?
Since installing Adobe Bridge CS3, I am unable to rename/copy/move folders within Windows explorer...If I want to do it, I have to use Bridge. This is particularly annoying when new folders have to be renamed/copied/moved within OTHER programs. Examp
-
Hi Experts, We want that in one order type of purchase order PO should be made from Info Record Price. Suppose info record price is Rs 5. Nobody should be able to make po in price 4.90 or 5.10. Please help me to achive the same. Regards GR
-
How do I take a photo and make it the shape of the object I choose, eg. oval, etc?
-
NEW FINAL CUT ISSUE PREVIEW DISABLED AND COLOR BARS AND NO CAPTURE ANYTHING
Well , few weeks ago I have the issue SEARCHING FOR MEDIA, I have to Downgrade all my editing computers to FCP 6.0.2, obviously I have to reinstall my OSX SYSTEM , a lot of time with no production, AND NOW a don't know what I do but when I try to cap
-
Does apple provide a download for Leapord 10.5?