5 Replies - 1767 Views - Last Post: 01 September 2010 - 07:58 AM Rate Topic: -----

#1 pallavi.manu  Icon User is offline

  • New D.I.C Head

Reputation: -15
  • View blog
  • 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  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • 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

Was This Post Helpful? 0
  • +
  • -

#3 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • 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.
Was This Post Helpful? 0
  • +
  • -

#4 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • 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. ;)
Was This Post Helpful? 0
  • +
  • -

#5 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Binary Tree Algorithm

Posted 01 September 2010 - 06:59 AM

Check this out
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10566
  • View blog
  • Posts: 39,107
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1