Click here to Skip to main content
Click here to Skip to main content

Data Structure Implementation to Query Binary Tree for Upline / Downline Node without using Recursion

By , 9 Dec 2010
 

Introduction

We are now and then faced with the problem with storing data corresponding to Binary Tree and querying it. We generally rely on Recursion (hence costly) to query tree structure. Here is a simple data structure change in order query tree structure using simple SQL statement - no Recursion required.

Background

There are situations when we want to store Nodes of binary tree in database with reference to its parent together with position (in this case, Left Node or Right Node of Parent). The problem arises when we want to query database to get upline node or downline Node w.r.t. a certain node, or we want to get the count of nodes present at each level in the b-tree.

You can think of an implementation of this code sample in creating data structure to keep members with their hierarchy for Multi-Level Marketing company.

Using the Code

The proposed solution has 2 data tables and 1 trigger.

Note: The field naming convention used below is a little awkward but it goes like - first 5 chars in field name correspond to table name, next 2 chars define data type, next 2 chars define Constraint, renaming letters are the name of field.

Table 1

  • tbl_BinaryTree_Nodes, primary table to keep Node details (say member details)

Fields:

  • Nodes_IN_PK_Code -- Primary Key of the table
  • Nodes_IN_FK_ParentCode -- Parent node
  • Nodes_CH_xx_Position -- Position under Parent node either Left Or Right
  • Nodes_VC_xx_NodeData -- Node Data -(more fields can be added to accommodate Node Data

Table 2

  • tbl_BinaryTree_Hierarchy, secondary table to keep Node hierarchy

Fields:

  • Hiera_IN_PK_Code -- primary key of the table
  • Hiera_IN_FK_ParentCode -- foreign key
  • Hiera_IN_FK_ChildCode -- foreign key
  • Hiera_CH_xx_Position -- Position under Parent node either Left Or Right
  • Hiera_IN_xx_NodeLevel -- Node Level under tree

Trigger 1

trg_BinaryTree_Nodes_ADD, to update Tree hierarchy for later query

The SQL to create tables and trigger is as follows:

Create Table tbl_BinaryTree_Nodes
(
    Nodes_IN_PK_Code Int Identity(1,1) Constraint PK_Nodes Primary Key,
    Nodes_IN_FK_ParentCode Int Constraint _
	FK_Nodes_To_Nodes References tbl_BinaryTree_Nodes (Nodes_IN_PK_Code ),
    Nodes_CH_xx_Position Char(1) Not Null Constraint CH_Nodes_Position Check _
	(Nodes_CH_xx_Position = 'L' OR Nodes_CH_xx_Position = 'R'),
    Nodes_VC_xx_NodeData Varchar(50)
)
GO

Create Table tbl_BinaryTree_Hierarchy
(
    Hiera_IN_PK_Code Int Identity(1,1) Constraint PK_Hiera Primary Key,
    Hiera_IN_FK_ParentCode Int Constraint _
	FK_Hiera_Nodes_Parent References tbl_BinaryTree_Nodes(Nodes_IN_PK_Code ),
    Hiera_IN_FK_ChildCode Int Constraint FK_Hiera_Nodes_Child References _
	tbl_BinaryTree_Nodes(Nodes_IN_PK_Code ),
    Hiera_CH_xx_Position  Char(1) Not Null Constraint CH_Hiera_Position Check _
	(Hiera_CH_xx_Position = 'L' OR Hiera_CH_xx_Position = 'R'),
    Hiera_IN_xx_NodeLevel int
)
GO

Create Trigger trg_BinaryTree_Nodes_ADD
On tbl_BinaryTree_Nodes
For Insert
AS
Begin
    IF (@@RowCount=1)
        Begin
            Insert Into tbl_BinaryTree_Hierarchy
                (Hiera_IN_FK_ParentCode, Hiera_IN_FK_ChildCode, _
		Hiera_CH_xx_Position, Hiera_IN_xx_NodeLevel)
            Select (Case When Hiera_IN_FK_ParentCode Is Null _
		Then Hiera_IN_FK_ChildCode Else Hiera_IN_FK_ParentCode  End), 
                    (Select Nodes_IN_PK_Code From Inserted), _
			(Case When Hiera_IN_FK_ParentCode Is Null _
			Then (Select Nodes_CH_xx_Position From Inserted) _
			Else Hiera_CH_xx_Position End) , 
                    (Hiera_IN_xx_NodeLevel + 1 )
                From tbl_BinaryTree_Hierarchy Where Hiera_IN_FK_ChildCode = _
			(Select Nodes_IN_FK_ParentCode From Inserted)
            Union ALL
            Select NULL , Nodes_IN_PK_Code , Nodes_CH_xx_Position , 1 From Inserted 
        End
    Else
        Begin
            RaisError ('Multiple Insertion Not Handled in Trigger to _
				update tbl_BinaryTree_Hierarchy',1,1)
            -- Code Using Cursor for Multiple insert
            --... 
            --...
            --...
            --
        End
End
GO 

SQL Queries

We will populate the database with sample data for queries. We are going to create a Tree as shown below:

 --'------------------------------------------
--'          The Binary Tree Representation
--'------------------------------------------
--'                 RootNode
--'             --------|-------
--'             |              |
--'            AL1            AL2
--'       -----|-----
--'       |          |
--'      AL2        AR2
--'   ---|---
--'  |       |
--' AL3     AR3
--'------------------------------------------

The SQL to generate the above Tree is as given below:

Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(Null,'L','Root Node')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(1,'L','AL1')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(1,'R','AR1')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(2,'L','AL2')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(2,'R','AR2')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(4,'L','AL3')
GO
Insert Into tbl_BinaryTree_Nodes (Nodes_IN_FK_ParentCode, Nodes_CH_xx_Position, _
	Nodes_VC_xx_NodeData) Values(4,'R','AR3') 
-- A. Get All Nodes directly under current Node
Select B.Nodes_VC_xx_NodeData, Hiera_IN_xx_NodeLevel From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ChildCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode=1 

-- B. Get All Nodes directly under current Node in left side
Select B.Nodes_VC_xx_NodeData, Hiera_IN_xx_NodeLevel From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ChildCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode=1 And H.Hiera_CH_xx_Position ='L'

-- C. Get All Nodes directly under current Node in right side
Select B.Nodes_VC_xx_NodeData, Hiera_IN_xx_NodeLevel From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ChildCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode=1 And H.Hiera_CH_xx_Position ='R'

-- D. Get All Nodes directly above the current 
Select B.Nodes_VC_xx_NodeData, Hiera_IN_xx_NodeLevel From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ChildCode=7

-- E. Get count of Nodes at each level under a specific node
Select Hiera_IN_xx_NodeLevel, count(*) From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ChildCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode=1 
Group By Hiera_IN_xx_NodeLevel

-- F. To find out the Nodes which got balanced due to new node entry
-- Lets us assume that the newly added node is AR3 - (which makes AL2 balanced)
-- We can use simple SQL Query or Common Table Expressions (CTE) 
-- on SQL 2005 to get the data
-- SQL Using Common Table Expressions (CTE) on SQL 2005
With CTE as (
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, _
	Hiera_IN_xx_NodeLevel as NodeLevel, 
      '' as IsBalanced,
   Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'L' and _
	Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) _
	as TotalLeftChild,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'R' and _
	iera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) _
	as TotalRightChild
From tbl_BinaryTree_Hierarchy H 
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = B.Nodes_IN_PK_Code

Where H.Hiera_IN_FK_ParentCode   is NOT NULL and H.Hiera_IN_FK_ChildCode = 7   
					-- (Primary key of Newly Added Node) 
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel,
Case   When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and _
	(CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then _
	'Yes' Else' No' End As IsBalanced, 
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild
From CTE 

Some More Queries - 2

 --'------------------------------------------
--' TREE 2
--'  The Binary Tree Representation  Tree - 2 
--'------------------------------------------
--'                 RootNode
--'             --------|-------
--'             |              |
--'            AL              AR
--'       -----|-----      -----|-----
--'       |          |     |          |
--'      ZL         ZR     BL        BR
--'                      ---|---   ---|---
--'                     |       |  |      |
--'                    CL      CR  DL     *DR*
--'------------------------------------------ 

A. How To Find the Balanced Node due to New Node Entry (with Reference to Tree -2)

Let us assume that the newly added node is *DR* - (which makes AR, BR balanced).

We can use a simple SQL Query or Common Table Expressions (CTE) on SQL 2005 to get the data:

With CTE as (
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, _
	Hiera_IN_xx_NodeLevel as NodeLevel, 
      '' as IsBalanced,
   Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'L' and _
	Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) _
	as TotalLeftChild,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'R' and _
	Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) _
	as TotalRightChild
From tbl_BinaryTree_Hierarchy H 
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = _
	B.Nodes_IN_PK_Code

Where H.Hiera_IN_FK_ParentCode   _
is NOT NULL and H.Hiera_IN_FK_ChildCode = 7   -- (Primary key of Newly Added Node) 
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel,
Case   When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and _
	(CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then 'Yes' Else' No' _
	End As IsBalanced, 
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild
From CTE

B. Finding Extreme Left & Right Leaf of Node (with Reference to Tree -2)

To add new node below any node to either its extreme right or extreme left, you just need to know the last node (Leaf) in the corresponding side. This you can get using the simple SQL Query.

For example, in the Tree above, extreme right of root is *DR*, and extreme left is ZL. Similarly, extreme right of Node AR is *DR* and extreme Left is CL.

;with CTE (ExtremeNode, Position, NodeLevel  )As 
(
    Select Hiera_IN_FK_ChildCode, Hiera_CH_xx_Position, 1 from  tbl_BinaryTree_Hierarchy 
            where Hiera_IN_xx_NodeLevel=2 and Hiera_IN_FK_ParentCode = _
		?ParentNodePK?  and Hiera_CH_xx_Position = ?LegSide?
    UNION ALL
    Select Hiera_IN_FK_ChildCode, Hiera_CH_xx_Position , CTE.NodeLevel + 1   _
		from  tbl_BinaryTree_Hierarchy 
            INNER JOIN CTE  ON CTE.ExtremeNode = Hiera_IN_FK_ParentCode _
		and CTE.Position = Hiera_CH_xx_Position
            where Hiera_IN_xx_NodeLevel = 2

)
Select Top 1 *  From CTE order By NodeLevel Desc; 

C. To get Node List which became balanced nodes due to new insertion (with reference to Tree -2 and For MLM Commission Payment)

When *DR* is added, then BR & AR get paid - but how much is not clear - According to general MLM trend, we can figure out that BR will get benefit of 1 Pair, and AR will get benefit of 1 pair.

We need to find out the list of parent Nodes w.r.t. the newly added node which will get benefit.

Now to get the list of nodes that needs to be paid is as follows.

The SQL Query below will give you the list of all the parents with last column ShouldIPay (Pay or DoNotPay) indicating which parent node needs to be paid (modify field list according to need).

With CTE as (
  Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, _
	Hiera_IN_xx_NodeLevel as NodeLevel, _
	Hiera_CH_xx_Position as Position, '' as IsBalanced,
    Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
    (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'L' and _
	Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalLeftChild,
    (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy _
	Where Hiera_CH_xx_Position = 'R' and _
	Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalRightChild
  From tbl_BinaryTree_Hierarchy H 
  Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = _
	B.Nodes_IN_PK_Code
  Where H.Hiera_IN_FK_ParentCode   is NOT NULL and _
	H.Hiera_IN_FK_ChildCode = ?PKofNewnode?   -- (Primary key of Newly Added Node) 
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel, CTE.Position,
Case   When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) _
	and (CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) _
	then 'Yes' Else' No' End As IsBalanced, 
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild,
Case   When Position ='L' then (Case When TotalLeftChild<=TotalRightChild _
	Then 'PAY' Else 'Do Not Pay' End ) 
       When Position ='R' then (Case When TotalLeftChild>=TotalRightChild _
	Then 'PAY' Else 'Do Not Pay' End ) 
        End As ShouldIPay
From CTE 

The tables can be easily modified to keep additional information w.r.t. information of node, however the basic fields will remain the same.

Currently, the trigger is written for single insertion only, we can modify trigger to handle bulk insert. We have to write Trigger to handle Node shifting to modify hierarchy table.

History

  • Revision 1: Some more queries - 2 sections added

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

AnupKumarYadav
Software Developer (Senior) e-Xseed Technologies & Devices Pvt. Ltd.
India India
AnupKumarYadav
Ranchi,Delhi,India
 
Sr. S/W Engineer
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionNeed query for Inserting a node?memberArpit Gandhi11-Apr-13 5:35 
Hi,
 
Very good article. I am trying to figure out how to insert a node in the tree. Can you provide me with a query so that either added node is on the right or left side, but the tree should remain balanced.
 
Thanks a lot again.
QuestionMULTI-LEVEL MARKETING DTABASE SCHEMAmemberMember 961038322-Nov-12 21:47 
Hi sir, I'm into developing my Multi-Level Marketing when someone says that my database structure is now properly analyze. Can you lend me your help on how to correct my database structure?
QuestionMULTI-LEVEL MARKETINGmemberMember 961038322-Nov-12 21:42 
Hi sir, I'm into developing my Multi-Level Marketing when someone says that my database structure is now properly analyze. Can you lend me your help on how to correct my database structure?
QuestionDear all thanks for the appreciationmemberAnupKumarYadav1-Jul-12 20:28 
Thanks every one for the appreciation. I am quite busy these days, however I'll respond to all of your queries very soon.
thanks all
AnupKumarYadav
Delhi,India

Questionhow can i impliment in visual studio?memberPKriyshnA26-May-12 4:18 
How can i use Trigger in Visual Studio...
i am a new for .net work please help
AnswerRe: how can i impliment in visual studio?memberAnupKumarYadav1-Jul-12 20:50 
The article above is SQL implementation of the solution. No .Net involved in here.
thanks
AnupKumarYadav
Delhi,India

Questionbinary treememberrajeev kumar pandey17-Mar-12 0:03 
how to create binary tree in asp.net c#
please give me graphical representation
AnswerRe: binary treememberAnupKumarYadav1-Jul-12 20:47 
There are more than one way to graphically represent the tree.
Please wait a while. I'll upload the solution ASAP.
Thanks
AnupKumarYadav
Delhi,India

QuestionHow to create payout table & how to generate payout weekly.memberVijaya Tiwari9-Mar-12 22:19 
Please help to generate the weekly payout i had followed ur data structure which is given this article
Please help i will be highly appreciable,
 
thanks
Questionhow to display tree in asp.net c#membershakawat hossain12-Oct-11 23:08 
dear sir
plz help me to draw binary tree . asp.net and c#.from ur database what u gave already in article
QuestionSuperfast B-tree order 3 (unrolled) in CmemberSanmayce2-Sep-11 6:21 
Hi AnupKumarYadav,
at link below there is something that exterminates all little drawbacks let alone recursion, that is, there is an unrolled b-tree with its own simulated stack:
http://www.sanmayce.com/Downloads/Leprechaun_%5Bquadrupleton%5D_r13_7pluses_ELFs_EXEs.zip[^]
 
I have wasted a ton of time in Binary trees and in my view they are not to be used in serious/heavy tasks, so you are welcome to see a skeleton of one heavy-duty approach: hashing as first level and millions of b-trees as second in order to blur-the-objects around.
 
There B-tree of order 3 is implemented in plain C, without delete operation. Talking of speed performance: it screams.
 
I also made an external b-tree implementation, I would be glad to hear from you what is your view on how this approach can be boosted:
http://www.sanmayce.com/Fastest_Hash/Sam%20Obernik%20-%20Work%20Of%20Art/Leprechaun_quadrupleton_r14_minus_C+EXE+PDF.zip[^]
 
Georgi
QuestionCan we use the same system for 3 Nodes with some variations ?memberimrankasuri28-Jul-11 21:02 
Dear Anup Kumar Yadav, can we use the same data structure for 3 nodes under one parent? i means L R and C (center node). will it be suitable to use by modifying little things in queries ? can you guide me which queries will need to modify to achieve that target ?
AnswerRe: Can we use the same system for 3 Nodes with some variations ?memberAnupKumarYadav1-Jul-12 20:35 
Yes imran we can.
AnupKumarYadav
Delhi,India

Generalhow can i get only four levels node ?membersuperb127-May-11 0:32 
Hello sir, I need help that how could we get the 4 levels of nodes
from a node, like Under Node 3 has many levels but i need only
4 levels nodes only.
hope u can understand what i need.
 
With regards
vik
GeneralRe: how can i get only four levels node ?memberAnupKumarYadav1-Jul-12 20:44 
Select B.Nodes_VC_xx_NodeData, Hiera_IN_xx_NodeLevel From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ChildCode  = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode=1
and Hiera_IN_xx_NodeLevel<=5
 
change Hiera_IN_xx_NodeLevel<=5 , value 5 to what ever according to your need
AnupKumarYadav
Delhi,India

GeneralThanks a lot...memberMember 76895495-Mar-11 18:30 
Hello Mr.Anup Kumar,your article helped me a lot to proceed in my project from the very first day.
I here by thank you for everything.
 
My client requirements are however with some differences so,i request you to help me out there so that i can conclude with my work efficiently.
GeneralRe: Thanks a lot...memberAnupKumarYadav6-Mar-11 6:15 
Thanks for appreciation. you can get in touch with me on anupkumaryadav@yahoo.com
AnupKumarYadav
Delhi,India

AnswerRepresenting Tree In Graphical format using 1-Dimensional ArraymemberAnupKumarYadav24-Dec-10 4:57 
If We can get data is 1-Dimensional array, then we can easily show it in Graph.
----------------------------------------------------------------------------------
| Root | AL | AR | ZL | ZR | BL | BR | ? | ? | ? | ? | CL | CR | DL | DR |.....
----------------------------------------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |......
----------------------------------------------------------------------------------
This can be acheived using DataTable or Recordset or Cursor, in this manner
Position | Node Data | other fields ...
1 | Root node |
2 | AL |
3 | AR |
4 | ZL |
5 | ZR |
6 | BL |
7 | BR |
8 | ? |
9 | ? |
10 | ? |
11 | ? |
12 | CL |
13 | CR |
14 | DL |
15 | DR |
 
------------------------------------- Changes Needed --------------------------------------------------
 
Add Column Hiera_IN_xx_TreePosition -- Node Location in 2-Dimensional Array w.r.t parent
In the Table tbl_BinaryTree_Hierarchy, secondary table to keep Node hierarchy
 
And Modify Trigger to update the newly column,
 
Create Trigger [dbo].[trg_BinaryTree_Nodes_ADD]
On [dbo].[tbl_BinaryTree_Nodes]
For Insert
AS
Begin
IF (@@RowCount=1)
Begin
Insert Into tbl_BinaryTree_Hierarchy
(Hiera_IN_FK_ParentCode, Hiera_IN_FK_ChildCode, Hiera_CH_xx_Position, Hiera_IN_xx_NodeLevel, Hiera_IN_xx_TreePosition)
Select (Case When Hiera_IN_FK_ParentCode Is Null
Then Hiera_IN_FK_ChildCode
Else Hiera_IN_FK_ParentCode End),
(Select Nodes_IN_PK_Code From Inserted),
(Case When Hiera_IN_FK_ParentCode Is Null
Then (Select Nodes_CH_xx_Position From Inserted)
Else Hiera_CH_xx_Position End) ,
(Hiera_IN_xx_NodeLevel + 1 ),
--New Change To incorporate Tree Placement w.r.t Parent
(Case When (Select Nodes_CH_xx_Position From Inserted)='L'
Then (Hiera_IN_xx_TreePosition*2)
Else ((Hiera_IN_xx_TreePosition*2)+1) End)

From tbl_BinaryTree_Hierarchy Where Hiera_IN_FK_ChildCode = (Select Nodes_IN_FK_ParentCode From Inserted)
Union ALL
Select NULL , Nodes_IN_PK_Code , Nodes_CH_xx_Position , 1, 1 From Inserted
End
Else
Begin
RaisError ('Multiple Insertion Not Handled in Trigger to update tbl_BinaryTree_Hierarchy',1,1)
-- Code Using Cursor for Multiple insert
--...
--...
--...
--
End
End
 
-- Now you can use simple query to get 1-dimensional representation to easily show in graphical format
 
----------------------------------------------------------------------------------
| Root | AL | AR | ZL | ZR | BL | BR | ? | ? | ? | ? | CL | CR | DL | DR |.....
----------------------------------------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |......
----------------------------------------------------------------------------------
 
Select * From tbl_BinaryTree_Hierarchy where (Hiera_IN_FK_ParentCode=1 or
(Hiera_IN_FK_ParentCode is Null And Hiera_IN_FK_ChildCode=1))
 
Or
 

Select * From tbl_GraphPosition_GrPos
Left outer join tbl_BinaryTree_Hierarchy on GrPos_IN_xx_Position = Hiera_IN_xx_TreePosition
and (Hiera_IN_FK_ParentCode=1 or (Hiera_IN_FK_ParentCode is Null And Hiera_IN_FK_ChildCode=1))
 
--------------
Data Table thus returned can be easily shown in Labels
 
Label1.Text = DataTable.Rows(0).item("FieldToDisplay") -- first node (root Node)
Label2.Text = DataTable.Rows(1).item("FieldToDisplay") -- 2nd node (AL)
:
:
LabelN.Text = DataTable.Rows(N-1).item("FieldToDisplay")
 

 
I regret because the codes are scattered every where in this article , I will update the entire article when I need enough time & I feel to do so.
 
I Hope This will help Wink | ;-)
AnupKumarYadav
Delhi,India

QuestionDaily Calculation...???membersuperb116-Dec-10 22:38 
Hello sir, i m totally new in this MLM project.
well i have done the placement of the nodes correctly.
 
well my requirement is the user can registered as a 1 head, 3 heads, 7 heads and 11 headers
 
and can place where he wants.
and the payouts like if header 1 or 3 then (total new pairs * 500) and for
7 or 11 ( (total new pairs * 1000) and update their field.
*how i can get the total new pairs also...??
 
*i have to do daily calculation from the root at 11:55 pm
I would like to know how can i do daily binary calculation ?
or any suggestion that how can i get to know about how many nodes has been added from each
 
node and how much commission has to be paid them after calculate the pairs.
 

More is it is good approach to use auto increment column name-> Nodes_IN_PK_Code in
 
tbl_BinaryTree_Nodes ?
 
hope you can understand my requirement.
with regards
vikram
AnswerRe: Daily Calculation...???memberAnupKumarYadav18-Dec-10 20:13 
What do you mean by 1/3/7/11 Head ? You need to add a Timestamp or DateTime Column to keep the joining date and query the data base with Date range in Where Clause to get joining for the specified period.
AnupKumarYadav
Delhi,India

GeneralRe: Daily Calculation...???membersuperb119-Dec-10 18:23 
Thanks for reply.
My apologies if i unable to clear my requirement.
Well i read your following *Query which give me left count and righ count of the node and
 
message to PAY... i would like to know how can i update in my table tbl_BinaryTree_Nodes
 
column name Left_count and Right_count using below *Query and how i get to know that how
 
much i have to pay ? e.g. according to node no.3 he added on his first day 3 and 5 and he
 
got according to pairs 3 and (3*500)=1500, now on his 2nd day he joined 5 and 8 and it will
 
be 2 and (2*500)=100...
*farmula
(Prev_left,Prev_right) and (Newleft,NewRight)
find min. from(Prev_left,Prev_right) and from (Newleft,NewRight)
acc. to below values.(initial values(0,0))
1st day (0,0) (3,5) = (3-0) = 3
2nd day (3,5) (5,8) = (5-3) = 2
Date left_count right_Count
12/12/2010 3 5
13/12/2010 5 8
 

----------------------------------------------------------------------------------------------
*Query
 
With CTE as (
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData,
 
Hiera_IN_xx_NodeLevel as NodeLevel, Hiera_CH_xx_Position as Position, '' as IsBalanced,
Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
(Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where
 
Hiera_CH_xx_Position = 'L' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as
 
TotalLeftChild,
(Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where
 
Hiera_CH_xx_Position = 'R' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as
 
TotalRightChild
From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode is NOT NULL and H.Hiera_IN_FK_ChildCode = ?PKofNewnode?
 
-- (Primary key of Newly Added Node)
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel, CTE.Position,
Case When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and
 
(CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then 'Yes' Else' No' End As
 
IsBalanced,
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild,
Case When Position ='L' then (Case When TotalLeftChild<=TotalRightChild Then 'PAY' Else
 
'Do Not Pay' End )
When Position ='R' then (Case When TotalLeftChild>=TotalRightChild Then 'PAY' Else
 
'Do Not Pay' End )
End As ShouldIPay
From CTE
----------------------------------------------------------------------------------------------
 
and about 1, 3, 7, 11 its a node type e.g if i joined 3 then i can get three node e.g
1(R) (L)2 (R))3, if i joined 7 then 1(R) (L)2 (R)3 (L)4(under 2) (R)5(under 3) and so on...
 
i have to calculate it binary calculation according to type
like if some joined 1 or 3 type then he will get the money per node is 500 and if 7 or 11 then 1000..hope you understand what i want to achieve and let me know ur suggestion too.
with regards
vik
 

AnswerRe: Daily Calculation...???memberAnupKumarYadav19-Dec-10 19:36 
The payment problem can be solved in many ways
 
Way 1 - by adding 4 column in tbl_BinaryTree_Nodes
Fields - PaidLeft , PaidRight, UnPaidLeft, UnpaidRight
Step A : Update Column UnPaidLeft & UnpaidRight -- Use trigger to increment the values when any new entry is made under this node upto level which is payable (if unlimited depth then always)
Step B : Now when you calculate payout then update column PaidLeft , PaidRight by decrementing Column UnPaidLeft & UnpaidRight by the numbers you are going to pay.
 

 
Way 2 - By adding Paid Column in tbl_BinaryTree_Hierarchy indicating that payout against this node has been paid or not.
 
Way 3 - Use data from the payout table to calculate & distribute payout.
 
In both way you need to add DateTime Column either in tbl_BinaryTree_Nodes or in tbl_BinaryTree_Hierarchy to query acc. to joining date.
AnupKumarYadav
Delhi,India

GeneralRe: Update Column..?membersuperb119-Dec-10 21:49 
how can i update the left and right column of the table using below CTE Query ..?
 
------------------------------------------------------------------------------------------
With CTE as (
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, Hiera_IN_xx_NodeLevel as NodeLevel, Hiera_CH_xx_Position as Position, '' as IsBalanced,
Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
(Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'L' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalLeftChild,
(Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'R' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalRightChild
From tbl_BinaryTree_Hierarchy H
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode is NOT NULL and H.Hiera_IN_FK_ChildCode = ?PKofNewnode? -- (Primary key of Newly Added Node)
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel, CTE.Position,
Case When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and (CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then 'Yes' Else' No' End As IsBalanced,
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild,
Case When Position ='L' then (Case When TotalLeftChild<=TotalRightChild Then 'PAY' Else 'Do Not Pay' End )
When Position ='R' then (Case When TotalLeftChild>=TotalRightChild Then 'PAY' Else 'Do Not Pay' End )
End As ShouldIPay
From CTE
AnswerRe: Update Column..?memberAnupKumarYadav20-Dec-10 4:24 
You don't need this Query, Just Modify the Triggers "trg_BinaryTree_Nodes_ADD", so that It update all the parent node on entry of any node.
AnupKumarYadav
Delhi,India

AnswerRe: Update Column..?memberAnupKumarYadav20-Dec-10 4:24 
You don't need this Query, Just Modify the Triggers "trg_BinaryTree_Nodes_ADD", so that It update all the parent node on entry of any child node.
AnupKumarYadav
Delhi,India

QuestionHow can we show it in Graphical Formmemberaktiwari2513-Dec-10 22:37 
Could you please help on this question I would be highly thankful to you.
AnswerRe: How can we show it in Graphical FormmemberAnupKumarYadav14-Dec-10 18:22 
Please elaborate your question w.r.t technology & envorinment.
AnupKumarYadav
Delhi,India

QuestionRe: How can we show it in Graphical Formmemberaktiwari2517-Dec-10 14:35 
Actually I am developing an MLM website in Asp.net(3.5) and C#. I have used your data structure for binary tree, I am able to show the hierarchy in Grid View using your querry but my client want that I should show it in Graphical repersentation form.
 
Could u please help me on this that how could I perform this, I am unable to do it on my own. Any help would highly appreciated.
 

regards
Abhishek
AnswerRe: How can we show it in Graphical FormmemberAnupKumarYadav18-Dec-10 20:22 
If You are using Asp.net then first decide the level of genealogy that you want to show, you can use Label/Link Label control to display names, Image to display image of member either depending on package , For this what you have to do is write a query to get the immediate child in left/right side & display it in label.
AnupKumarYadav
Delhi,India

GeneralRe: How can we show it in Graphical Formmemberaktiwari2518-Dec-10 21:08 
Thanks for your reply I have adapted two methods to show the genealogy in one I have used built in tree control in asp.net and the second was the method you have already suggested.
 
Honestly speaking your data structure help me a lot. Keep writing such article and if I wud hav any issue again please reply on this forum.
 
Thanks once again and I must say I have searched all the big and small places on internet to find such data structure but only you have written. Great dude!!! Laugh | :laugh:
 
Regards
Abhishek
AnswerRe: How can we show it in Graphical FormmemberAnupKumarYadav19-Dec-10 2:47 
See, Displaying the tree need some SQL query & Some sort of Code in Webpage And its up to you how yo do it. For Your Reference you can check this image at http://www.anupkumaryadav.com/tree.gif[^] to get a flavor of the tree.
AnupKumarYadav
Delhi,India

GeneralRe: How can we show it in Graphical Formmemberaktiwari2519-Dec-10 5:05 
Thanks for your quick reply. I would be higly thankful to you if you share code for the same to generate a tree as you have shared in link.
GeneralRe: How can we show it in Graphical Formmembersuperb123-Dec-10 22:48 
Well could you let me know how can i achieve to display genealogy ...?
any example or code...?
AnswerRe: How can we show it in Graphical Form [modified]memberAnupKumarYadav24-Dec-10 4:33 
Representing Tree In Graphical format
 

Starting with Universal Rule "There are many ways to do a certain thing". Here is one way to represent Binary tree in graphical format.
 
With reference to binary tree representation above (Tree 2)
 

 
----------------------------------------------------------------------------------
| Root | AL | AR | ZL | ZR | BL | BR | ? | ? | ? | ? | CL | CR | DL | DR |.....
----------------------------------------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |......
----------------------------------------------------------------------------------

 
We Just need a query which can arrange the data in an array in this case DataTable with multiple row.
 
data can be retrived in 2 format,
 
1 - without row for missing node eg.
 

Position | Node Data | other fields ...
1 | Root node |
2 | AL |
3 | AR |
4 | ZL |
5 | ZR |
6 | BL |
7 | BR |
12 | CL |
13 | CR |
14 | DL |
15 | DR |

For the above rresult , we can use the code below
 

 

;With CTE ( Code, NodeData, Position, LeftRight) AS
(
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, 1 , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
Where Nodes_IN_PK_Code=1
Union ALL
(
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, (Position * 2) , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
join CTE on tbl_BinaryTree_Nodes.Nodes_IN_FK_ParentCode = CTE.Code And Nodes_CH_xx_Position ='L'
 
Union All
 
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, ((Position * 2) + 1 ) , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
join CTE on tbl_BinaryTree_Nodes.Nodes_IN_FK_ParentCode = CTE.Code And Nodes_CH_xx_Position ='R'
)
)
Select * From CTE Order by Position
 

 
2 - With rows for missing Nodes eg.
 

Position | Node Data | other fields ...
1 | Root node |
2 | AL |
3 | AR |
4 | ZL |
5 | ZR |
6 | BL |
7 | BR |
8 | ? |
9 | ? |
10 | ? |
11 | ? |
12 | CL |
13 | CR |
14 | DL |
15 | DR |

 
For the above result set we can create a table for example
 

Create Table tbl_GraphPosition_GrPos
(
GrPos_IN_PK_Code int Identity(1,1),
GrPos_IN_xx_Position Int
)

 
Insert Rows with values Natural Numbers from 1 to n , where n is the nth node you want to display in tree. For example to show tree like below we will insert 15 rows.
 

--'------------------------------------------
--' X
--' --------|-------
--' | |
--' X X
--' -----|----- -----|-----
--' | | | |
--' X X X X
--' ---|--- ---|--- ---|--- ---|---
--' | | | | | | | |
--' X X X X X X X X
--'------------------------------------------

 
Now the qwuery below will give use required DataTable
 

;With CTE ( Code, NodeData, Position, LeftRight) AS
(
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, 1 , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
Where Nodes_IN_PK_Code=1
Union ALL
(
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, (Position * 2) , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
join CTE on tbl_BinaryTree_Nodes.Nodes_IN_FK_ParentCode = CTE.Code And Nodes_CH_xx_Position ='L'
 
Union All
 
Select Nodes_IN_PK_Code, Nodes_VC_xx_NodeData, ((Position * 2) + 1 ) , Nodes_CH_xx_Position From tbl_BinaryTree_Nodes
join CTE on tbl_BinaryTree_Nodes.Nodes_IN_FK_ParentCode = CTE.Code And Nodes_CH_xx_Position ='R'
)
)
Select CTE.* From CTE
Right outer join tbl_GraphPosition_GrPos on CTE.Position = tbl_GraphPosition_GrPos.GrPos_IN_xx_Position
Order By tbl_GraphPosition_GrPos.GrPos_IN_xx_Position

 

Now we can easily display the data in labels ,
For example using in ASP.Net
 
Label1.Text = DataTable.Rows(0).item("FieldToDisplay")
Label2.Text = DataTable.Rows(1).item("FieldToDisplay")
:
:
LabelN.Text = DataTable.Rows(N-1).item("FieldToDisplay")
 
I Hope This will help Wink | ;-)
 
Alternatively , We can Add One More column in tbl_BinaryTree_Hierarchy , to keep Node placement in 1-Dimensional Array of the Newly Inserted nodde w.r.t Parent Node. Which can be updated using the same trigger, at the time of node insertion thus saving us from using Computed Table to calcualte location during runtime thus resulting in lighter overhead to Server in the Query.
AnupKumarYadav
Delhi,India
modified on Friday, December 24, 2010 10:59 AM

GeneralRe: How can we show it in Graphical Formmemberaktiwari2518-Jul-11 1:04 
While I am running this query with Order by Clause
 Select * From CTE Order by Position
It shows error Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type int.
and when I run without Order By Clause It shows all the rows not limiting to 15 rows. Kindly resolve this issue I would be higly thankful to you.Thumbs Up | :thumbsup:
GeneralMy vote of 5memberaktiwari2513-Dec-10 22:35 
It's great to read and now I am ready to implement this in MY MLM project but one more help needed how we can show this in a graphical representation. Thanks in Advance
AnswerBetter way to do binary tressmember--CELKO--13-Dec-10 6:04 
I think this approach is needlessly complex and hard to use. Triggers and recursive CTEs are procedural code.
 
Look up a binary heap in an book on data structure. The idea is that if a parent node has an array position of (n), the the left and right children are at (2n) and (2n+1). I have a short discussion, with artwork at
 
http://www.simple-talk.com/sql/t-sql-programming/binary-trees-in-sql/
 
For fun, write code to balance a tree in this format.
--CELKO--

GeneralRe: Better way to do binary tressmemberAnupKumarYadav14-Dec-10 18:19 
Your Idea is very basic that in binary Tree if parent node has an array position of (n), the the left and right children are at (2n) and (2n+1) - similarly if the tree is tertiary then same parent node at n will have children at position (3n-1) , (3n) , (3n+1) - on this very idea if a tree in suppose m-ary (that is having m child) then a parent at position (n) will have Left most node at (m*n)-(m-2) , and right most node is (m*n) + 1 and the other nodes are in between them.
 

Infact, there are multiple ways to tackle the same problem - (each solution has some benefit over the other) - I had just shown one of the way to deal with the problem.
 
Moreover This procedure is not too complex at most - there are 2 Table & 1 Trigger for all, All the basic Query is being done using Simple Select statement , The Query which has been written using CTE can also be written using Select Statement,
for example consider the query A .How To find the Balanced node due to new node entry (with reference to Tree -2 )
 
With CTE as (
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, Hiera_IN_xx_NodeLevel as NodeLevel, 
      '' as IsBalanced,
   Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'L' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalLeftChild,
   (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'R' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalRightChild
From tbl_BinaryTree_Hierarchy H 
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = B.Nodes_IN_PK_Code
 
Where H.Hiera_IN_FK_ParentCode   is NOT NULL and H.Hiera_IN_FK_ChildCode = 7   -- (Primary key of Newly Added Node) 
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel,
Case   When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and (CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then 'Yes' Else' No' End As IsBalanced, 
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild
From CTE
 
The above code can also be written as
 

 
Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, Hiera_IN_xx_NodeLevel as NodeLevel, 
   
case when ((Power(2,Hiera_IN_xx_NodeLevel)-2/2) = (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'L' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code))
		and 
	((Power(2,Hiera_IN_xx_NodeLevel)-2/2)  =    (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'R' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code))
	then 'YES' Else 'NO' End as IsBalanced
From tbl_BinaryTree_Hierarchy H 
Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = B.Nodes_IN_PK_Code
Where H.Hiera_IN_FK_ParentCode   is NOT NULL and H.Hiera_IN_FK_ChildCode = 7   -- (Primary key of Newly Added Node) 
 
So, There are multiple ways , Choose your way carefully.
AnupKumarYadav
Delhi,India

Questionhow can we display the nodes visually in a graph?membersuperb111-Dec-10 1:09 
hello sir how can we display a tree view for each node or from particular node...??
with regards
vikram
Questionhow can we check ? [modified]membersuperb18-Dec-10 22:53 
Fig.1
--'------------------------------------------
--' The Binary Tree Representation
--'------------------------------------------
--' RootNode
--' --------|-------
--' | |
 
--'------------------------------------------
 
from the above diagram how can we insert in the Left side of the Root Node and same as for the Right side??
 
Fig.2
--'------------------------------------------
--' The Binary Tree Representation
--'------------------------------------------
--' RootNode
--' --------|-------
--' | |
--' AL1
--' | |
--' AL2 AR2
--' ---|---
--' | |
--' AL3 AR3
--' | |
--' (?)
--'------------------------------------------
 

According to Fig.2 how can insert into right side ?
how can we insert into left most(AL3(L) from the root at left side...?
 
hope u can understand what i need..?
 
*
Actually i would like to know how can add the node at the left end most and at the right end most?
if there is no node in the right side from the Root Node then how can we detect that there is no node in the right side from the ROOT NODE ? if there is node then how to detect the right end most and add the node after it.?

modified on Thursday, December 9, 2010 6:36 AM

AnswerRe: how can we check ?memberAnupKumarYadav9-Dec-10 17:09 
--'------------------------------------------
--'          The Binary Tree Representation
--'------------------------------------------
--'                 RootNode
--'             --------|-------
--'             |              |
--'            AL              AR
--'       -----|-----      -----|-----
--'       |          |     |          |
--'      ZL         ZR     BL        BR
--'                      ---|---   ---|---
--'                     |       |  |      |
--'                    CL      CR  DL     *DR*
--'------------------------------------------
 
To add new node below any node to either its extreme right or extreme left you just need to know the last node (Leaf) in the corresponding side. This you can get using the simple SQL Query.
 
For Eg. In the Tree above extreme right of root is *DR* , and extreme left is ZL.
similarly extreme right of Node AR is *DR* and extreme Left is CL.
 

-- This SQL will return extreme Left Or Right Node of any Parent node
 
;with CTE (ExtremeNode, Position, NodeLevel  )As 
(
    Select Hiera_IN_FK_ChildCode, Hiera_CH_xx_Position, 1 from  tbl_BinaryTree_Hierarchy 
            where Hiera_IN_xx_NodeLevel=2 and Hiera_IN_FK_ParentCode = ?ParentNodePK?  and Hiera_CH_xx_Position = ?LegSide?
    UNION ALL
    Select Hiera_IN_FK_ChildCode, Hiera_CH_xx_Position , CTE.NodeLevel + 1   from  tbl_BinaryTree_Hierarchy 
            INNER JOIN CTE  ON CTE.ExtremeNode = Hiera_IN_FK_ParentCode and CTE.Position = Hiera_CH_xx_Position
            where Hiera_IN_xx_NodeLevel = 2
 
)
Select Top 1 *  From CTE order By NodeLevel Desc;
 
-- Do vote & bookmark if it was helpful to you, thanks
AnupKumarYadav
Delhi,India

GeneralRe: how can we check ?membersuperb110-Dec-10 1:02 
Thanks sir. Its solve my problem regarding extreme Left Or Right Node.
Really u r genius...
with regards
vikram
AnswerRe: How to check commission for each above node? [modified]memberAnupKumarYadav1-Dec-10 20:53 
--'------------------------------------------
--'          The Binary Tree Representation
--'------------------------------------------
--'                 RootNode
--'             --------|-------
--'             |              |
--'            AL              AR
--'       -----|-----      -----|-----
--'       |          |     |          |
--'      ZL         ZR     BL        BR
--'                      ---|---   ---|---
--'                     |       |  |      |
--'                    CL      CR  DL     *DR*
--'------------------------------------------
 
Hi, with reference to your query & Tree above, what I conclude is that when *DR* is added then BR & AR gets paid - but how much is not clear - According to general MLM trend I can figure out that BR will get benefit of 1 Pair, and AR will get benefit of 1 pair.
 
Let us assume that you want to give benefit of 1 unit pair to BR and also to AR the benefit of 1 unit pair ( as you might had been already given the benefit of 1 unit pair when DL was added.)
 
So you need to find out the list of parent Nodes w.r.t the newly added node who will get benefit.
 
Let us assume the Primary Key of the newly added node (*DR*) is 123456.
Now to get the list of nodes who needs to be paid is as follows..
 
The SQL Query below will give you the list of all the parents with last column ShouldIPay (Pay or DoNotPay) indicating which parent node needs to be paid.
(for the sake of keeping the sql similar to the previous one I had just added the column "Hiera_CH_xx_Position" in the CTE & added a calculated column in the result set "ShouldIPay")
 
With CTE as (
  Select B.Nodes_IN_PK_Code as PK, B.Nodes_VC_xx_NodeData as NodeData, Hiera_IN_xx_NodeLevel as NodeLevel, Hiera_CH_xx_Position as Position, '' as IsBalanced,
    Power(2,Hiera_IN_xx_NodeLevel)-2 as TotalNodeForBalanceTree,
    (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'L' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalLeftChild,
    (Select Count(Hiera_IN_PK_Code) From tbl_BinaryTree_Hierarchy Where Hiera_CH_xx_Position = 'R' and Hiera_IN_FK_ParentCode=B.Nodes_IN_PK_Code) as TotalRightChild
  From tbl_BinaryTree_Hierarchy H 
  Left Outer Join tbl_BinaryTree_Nodes B on H.Hiera_IN_FK_ParentCode   = B.Nodes_IN_PK_Code
  Where H.Hiera_IN_FK_ParentCode   is NOT NULL and H.Hiera_IN_FK_ChildCode = 123456   -- (Primary key of Newly Added Node) 
)
Select CTE.PK, CTE.NodeData, CTE.NodeLevel, CTE.Position,
Case   When ((CTE.TotalNodeForBalanceTree / 2 = TotalLeftChild) and (CTE.TotalNodeForBalanceTree / 2 = TotalRightChild)) then 'Yes' Else' No' End As IsBalanced, 
CTE.TotalNodeForBalanceTree , CTE.TotalLeftChild , CTE.TotalRightChild,
Case   When Position ='L' then (Case When TotalLeftChild<=TotalRightChild Then 'PAY' Else 'Do Not Pay' End ) 
       When Position ='R' then (Case When TotalLeftChild>=TotalRightChild Then 'PAY' Else 'Do Not Pay' End ) 
        End As ShouldIPay
From CTE
 
Hope this solves your problem.
*Happy Coding*
AnupKumarYadav
Delhi,India
modified on Thursday, December 9, 2010 10:26 PM

GeneralRe: How to check commission for each above node?memberimrankasuri1-Dec-10 22:06 
Its really Nice and Great, i am very thankful.
GeneralMy vote of 5membersuperb124-Nov-10 23:53 
This article helps me alot..
thanks AnupKumarYadav.
with regards
vikram
GeneralRe: My vote of 5memberAnupKumarYadav25-Nov-10 2:56 
Thanks, Vikram - Please do vote,bookmark any article you liked in appreciation. This raises the joy of sharing.
AnupKumarYadav
Delhi,India

GeneralMy vote of 5membershailpd16-Nov-10 20:36 
Its a nice article to share with the people like us, thank you.
GeneralRe: My vote of 5memberAnupKumarYadav16-Nov-10 20:42 
my pleasure, Thanks
AnupKumarYadav
Delhi,India

GeneralMy vote of 5memberJai Prakash Mishra16-Nov-10 19:47 
Nice article. Thanks for sharing
GeneralRe: My vote of 5memberAnupKumarYadav16-Nov-10 20:41 
Thanks Jai, I am writing an article for Data Structure to create dynamically configurable Invoicing/Billing Structure . I'll inform you when I publish It.
AnupKumarYadav
Delhi,India

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 9 Dec 2010
Article Copyright 2010 by AnupKumarYadav
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid