# Binary Tree Algorithm

Page 1 of 1

## 5 Replies - 2057 Views - Last Post: 01 September 2010 - 07:58 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=188577&amp;s=c76967aab4ef847d70fb0311073b43f8&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 pallavi.manu

Reputation: -15
• Posts: 24
• Joined: 28-June 10

# Binary Tree Algorithm

Posted 01 September 2010 - 01:22 AM

```1.start
2.create a class tree having an integer variable val and having 2  pointers left and right.
3.Check if root == null then assign val to root.
4.else if (root!=null) && (root>val) then assign root.right=val.
5.else if (root!=null) &&(root <val) then assign root.left=val.
6.end of algorithm
```

Algorithm for inserting in to binary tree.Is this correct?
Is This A Good Question/Topic? 0

## Replies To: Binary Tree Algorithm

### #2 aamir.ramzan

Reputation: 3
• Posts: 28
• Joined: 12-January 10

## Re: Binary Tree Algorithm

Posted 01 September 2010 - 01:41 AM

You should make recursion function which has base condition like this
```Check if root.left == null && root.right == null then assign val to root.
```

and recursion should be something like this
```else if (root!=null) && (root>val) then pass val to right side pointer to function
else pass to left side
```

### #3 mostyfriedman

• The Algorithmi

Reputation: 727
• Posts: 4,473
• Joined: 24-October 08

## Re: Binary Tree Algorithm

Posted 01 September 2010 - 01:41 AM

your algorithm will only work if there's no root, or if there's a root but with no left and right nodes. It will not work for larger trees. Think recursively on this one.

### #4 m-e-g-a-z

• Winning

Reputation: 497
• Posts: 1,453
• Joined: 19-October 09

## Re: Binary Tree Algorithm

Posted 01 September 2010 - 01:52 AM

Usually I hate looking at code from this site but for simplicity, I think this would give you an idea of how you would structure it. Trees are a recursive data structure so make use of recursion.

### #5 KYA

• g++ jameson.cpp -o beverage

Reputation: 3151
• Posts: 19,194
• Joined: 14-September 07

## Re: Binary Tree Algorithm

Posted 01 September 2010 - 06:59 AM

Check this out

### #6 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 11310
• Posts: 42,591
• Joined: 27-December 08

## Re: Binary Tree Algorithm

Posted 01 September 2010 - 07:58 AM

I also have a Generic Tree Structure which covers insertion. It is designed for Nodes with n children, not specifically 2 though. It illustrates recursion well, though.

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }