Skip to main content
added 74 characters in body
Source Link
Robert Harvey
  • 200.8k
  • 55
  • 470
  • 683

Well you haveYour code, as written, will produce a tree that looks like this:

   5
  / \
 /   \
1     8
 \   /
  3 6
     \
      9

Yet you could haveA properly balanced tree looks like this:

     6
    / \
   /   \
  3     8
 / \     \
1   5     9

So, no. this is not balancing your binary tree. This is simply constructing a sorted binary tree with a balance that is totally dependent on the sequence of insertion.

Depending on the order of insert() calls you could easily end up building:

1
 \
  3
   \
    5
     \
      6
       \
        8
         \
          9

You have no code to rebalance the tree.

I recommend you give this a read:

http://www.stoimen.com/blog/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/

Well you have

   5
  / \
 /   \
1     8
 \   /
  3 6
     \
      9

Yet you could have

     6
    / \
   /   \
  3     8
 / \     \
1   5     9

So, no. this is not balancing your binary tree. This is simply constructing a sorted binary tree with a balance that is totally dependent on the sequence of insertion.

Depending on the order of insert() calls you could easily end up building:

1
 \
  3
   \
    5
     \
      6
       \
        8
         \
          9

You have no code to rebalance the tree.

I recommend you give this a read:

http://www.stoimen.com/blog/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/

Your code, as written, will produce a tree that looks like this:

   5
  / \
 /   \
1     8
 \   /
  3 6
     \
      9

A properly balanced tree looks like this:

     6
    / \
   /   \
  3     8
 / \     \
1   5     9

So, no. this is not balancing your binary tree. This is simply constructing a sorted binary tree with a balance that is totally dependent on the sequence of insertion.

Depending on the order of insert() calls you could easily end up building:

1
 \
  3
   \
    5
     \
      6
       \
        8
         \
          9

You have no code to rebalance the tree.

I recommend you give this a read:

http://www.stoimen.com/blog/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/

Source Link
candied_orange
  • 119.7k
  • 27
  • 233
  • 369

Well you have

   5
  / \
 /   \
1     8
 \   /
  3 6
     \
      9

Yet you could have

     6
    / \
   /   \
  3     8
 / \     \
1   5     9

So, no. this is not balancing your binary tree. This is simply constructing a sorted binary tree with a balance that is totally dependent on the sequence of insertion.

Depending on the order of insert() calls you could easily end up building:

1
 \
  3
   \
    5
     \
      6
       \
        8
         \
          9

You have no code to rebalance the tree.

I recommend you give this a read:

http://www.stoimen.com/blog/2012/07/03/computer-algorithms-balancing-a-binary-search-tree/