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 help
Try 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));
}
Similar Messages
-
Binary tree - a spesific node's height !
hello !
im looking for a method to deterine a certain node's hight in a binary tree (that is its distance from the root )
please enlighten me on how to do this if you can
thank you> Traverse the BT and with every step increase a
counter. When you get to the node you're looking for,
return the counter.
Or just add an attribute to you TreeNode class which holds the value for the degree/height of the node. -
Succinct encoding for binary tree with n nodes...
How do I find all possible bit strings (Succinct encoding) for a binary tree with order n? Can anybody give me an algorithm?
I associate the order of a tree with some sort of a search or traversal. What do you mean by a "+tree with order n+"?
Could you perhaps give an example of what you're looking for? -
Function Module to get the node name in particular level name in Hierarchy
Hi All,
We have 0Material hierarchy which consists of 14 levels and materials are in the 14th level.
We have a requirement to update the 4th level node name to all materials.
So we have created the attribute to this 0Material and thought of updating in the transformation.
Could you please suggest us to which function module i can in this scenario.
Thanks in advance,..
PrasannaCan you explain in more detail what exactly you want to do?
do you want to limit hierarchy to level4?
Regards
Sudeep -
Looping through all the Nodes at any Particular Level Specified
Dear Forum Members,
I have an XML File in the database in a Column of type XMLTYPE.
The Format is given below
<XML-SSDFILELIST>
<Training>
<BRKCD_STMNSWTINVIN_C Key="6707">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</BRKCD_STMNSWTINVIN_C>
<BRKCD_STREDSWTINVIN_C Key="6708">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</BRKCD_STREDSWTINVIN_C>
<VSACD_TIPER_C Key="7285">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSACD_TIPER_C>
<VSSCD_NTHRESPLA_C Key="6266">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_NTHRESPLA_C>
<VSSCD_QTHRESPLA_C Key="6267">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_QTHRESPLA_C>
<VSSCD_VDFL_C Key="6269">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_VDFL_C>
<VSSCD_VMAX_C Key="6270">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_VMAX_C>
<VSSCD_VMIN_C Key="6271">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_VMIN_C>
<VSSCD_VTHRESPLA_C Key="6272">
<FINISHED><![CDATA[This is a Finished data ]]></FINISHED>
<CONTACT-NUMBER><![CDATA[This is a CONTACT-NUMBER data ]]></CONTACT-NUMBER>
<DEFAULT></DEFAULT>
<MIN></MIN>
<MAX></MAX>
<UNIT></UNIT>
<FORMULA></FORMULA>
<FORMULA-DESC></FORMULA-DESC>
<ADVANCED-FORMULA></ADVANCED-FORMULA>
<INTERNAL-ADAPT-DESC></INTERNAL-ADAPT-DESC>
<DATA-DESC-REPORT></DATA-DESC-REPORT>
<REV-DESC></REV-DESC>
</VSSCD_VTHRESPLA_C>
</Training>
</XML-SSDFILELIST>
Is there any way I can Loop through all the Child records at 3rd Level(Bolded Level in the File).
Regards
Madhu.check this blog,
http://www.oracleappshub.com/11i/oracleapps-responsibility-vs-sap-functions/
Re: How to change OM responsibility as read-only in oracle applications 11i
read only responsibility-user -
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.
} -
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 -
How to check whether a node exist in a Particular Level. (xmltype)
hi,
please help me to check whether a particular node exists in one level.
for eg
I have the following xml
<map>
<entry>
<key>
heading1
</key>
<map>
<entry>
<key> sub1 heading1</key>
<value> sub1 heading1 value </value>
</entry>
<entry>
<key> sub2 heading1 </key>
<value> sub2 heading1 value </value>
</entry>
</map>
</entry>
<entry>
<key>
heading2
</key>
<map>
<entry>
<key> sub1 heading2</key>
<value> sub1 heading2 value </value>
</entry>
<entry>
<key> sub2 heading2 </key>
<value> sub2 heading2 value </value>
</entry>
</map>
</entry>
</map>i need to check how many heading exists in this xml.
I am checking like
i:=1;
l_section := ip_xml.extract('//map/entry');
WHILE l_section.existsnode('entry[' || i|| ']') = 1 LOOP
// extract the key name within entry tag
// print the key name.
i:=i+1;
end loop;but iam getting all the key name like
heading1
sub1 heading1
sub2 heading1
heading2
sub1 heading2
sub2 heading2
I need only heading1 and heading2. how can I check whether a particular node exist in particular level.
first level , second level etc. Please helpbut iam getting all the key nameThat's because you're using a descendant axis : //map/entry
SQL> DECLARE
2
3 ip_xml xmltype := xmltype('<map>
4 <entry>
5 <key>
6 heading1
7 </key>
8 <map>
9 <entry>
10 <key> sub1 heading1</key>
11 <value> sub1 heading1 value </value>
12 </entry>
13 <entry>
14 <key> sub2 heading1 </key>
15 <value> sub2 heading1 value </value>
16 </entry>
17 </map>
18 </entry>
19 <entry>
20 <key>
21 heading2
22 </key>
23 <map>
24 <entry>
25 <key> sub1 heading2</key>
26 <value> sub1 heading2 value </value>
27 </entry>
28 <entry>
29 <key> sub2 heading2 </key>
30 <value> sub2 heading2 value </value>
31 </entry>
32 </map>
33 </entry>
34 </map>');
35
36 BEGIN
37
38 for r in (
39 select heading, headno
40 from xmltable( '/map/entry/key'
41 passing ip_xml
42 columns heading varchar2(30) path '.'
43 , headno for ordinality )
44 )
45 loop
46 dbms_output.put_line('Heading '||r.headno||' = '||r.heading);
47 end loop
48 ;
49
50 END;
51 /
Heading 1 =
heading1
Heading 2 =
heading2
PL/SQL procedure successfully completed -
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);
} -
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 -
FINDING THE LARGEST NODE IN A BINARY TREE
can anybody help me with a recursive function to find the LARGEST NODE IN A BINARY TREE if you are given the following specs. PLEASE NOTE THAT IT'S A BINARY TREE NOT A SEARCH TREE.
Public class Node {
Node left;
Node right;
int val;
int Largest(Node r){
}Naah, just studying and thinking it's an interesting
task Well, I diagree.
since each time the recursive function is
called, variables you hve in the method will be over
written with the new recursive call.So what? For variables that are valid inside the scope of the method: that's how it supposed to be. Vor variables with a larger scope: hand them over as an additional argument. -
I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
public class BTNode {
private customer item;
private BTNode left;
private BTNode right;
public BTNode() {// constructor
item = null;
left = right = null;
public BTNode(customer newItem) {// constructor
item = newItem.clone();
left = right = null;
public void setItem(customer newItem) {// set methods
item = newItem.clone();
public void setLeft(BTNode newLeft) {
left = newLeft;
public void setRight(BTNode newRight) {
right = newRight;
public customer getItem() { // get methods
return item;
public BTNode getLeft() {
return left;
public BTNode getRight() {
return right;
public class Queue1 extends BTNode {
public Queue1() {
super();
public void enqueue(BTNode newItem) {
public void dequeue() {
}public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
You probably want to aggregate a List.
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 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();
} -
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
Maybe you are looking for
-
CA - Error when trying to generate an amended RL1 XML file
Dear Community, In case you try to generate an amended RL1 XML file and you get the error "Element content is invalid according to the DTD/Schema", it means the system incorrectly missed the tag corresponding to Box O. If you are facing this issue pl
-
I need some advice ..How would you..
I know I can ask this is in a dedicated Forum (of some sort)... but for now ...I am after quick and easy thoughts to start with. I want to make a "Home Page" for a retail IN STORE computer screen. Its for customers to access specific websites at the
-
ICloud Backup cannot begin, another device currently restoring...
When I bought my iPhone 4S on launch day, everything went really well with my iCloud backing up my info/data/contacts, however, I am having trouble with it now. I turned off "iCloud Backup", but have since decided to turn it back on in order to use i
-
No optical flow going from FCPX to Compressor
Using Compressor 4.1.3 and FCPX 10.1.4. When I export a project from FCPX to Compressor, and the project has some clips with Optical Flow, Compressor does not render those clips using Optical Flow. Using "Apple Devices HD (Best Quality)" setting. I s
-
Does the Nokia 5230 have an error logging system f...
Hi there, I was wondering whether the Nokia 5230 has an error logging system for diagnostics especially for troubleshooting apps and the OS, your answers would be much appreciated. Many thanks, RocknRollTim Solved! Go to Solution.