Results 1 to 2 of 2

Thread: Binary tree

  1. #1
    harmy is offline Member
    Join Date
    Dec 2010
    Posts
    1
    Rep Power
    0

    Default Binary tree

    Hi guys i'm having trouble understanding the following homework question.
    I have done most of the work, but don't get the sample output expected. This is probably because i have miss understood the way our professor wants us to insert Values. I have given my insert method and sample output. Can you guys see if i'm doing something wrong

    Home Work question
    Write a program called A02Q05 that accepts a series of integers as command line parameters. The
    integers should be inserted into a binary tree in the order that they occur in the series. In other
    words, the series is a level-by-level traversal.

    **Sample outPut**

    >java A02Q05 4 5 2 7 3 6 8
    preorder: 4 5 7 3 2 6 8
    inorder: 7 5 3 4 6 2 8
    postorder: 7 3 5 6 8 2 4

    **My Output**

    Preorder Traversal:
    4 2 3 5 6 7 8
    Inorder Traversal:
    2 3 4 5 6 7 8
    Postorder Traversal:
    2 3 5 6 7 8 4

    My insert Method
    Java Code:
          public void insert(Node newNode) {
     
            Node tempNode = null;
            Node rootNode = root;
     
            while (rootNode != null) {
                tempNode = rootNode;
     
                if (newNode.getKey() < rootNode.getKey()) {
                    rootNode = rootNode.getLeftChild();
                } else {
                    rootNode = rootNode.getRightChild();
                }
            }
     
            newNode.setParent(tempNode);
     
            if (tempNode == null) {
                root = newNode;
            } else if (newNode.getKey() < tempNode.getKey()) {
                tempNode.setLeftChild(newNode);
            } else {
                tempNode.setRightChild(newNode);
            }
          }
    Cheers

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,452
    Rep Power
    20

    Default Re: Binary tree

    Homework doesn't belong in 'Advanced Java'. Moving to 'New to Java'

    db
    Last edited by DarrylBurke; 02-03-2012 at 09:53 AM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Binary Tree Help - Find the largest sub-tree
    By joshhazel in forum New To Java
    Replies: 2
    Last Post: 01-30-2012, 03:08 AM
  2. binary tree
    By Dedo in forum Advanced Java
    Replies: 15
    Last Post: 05-26-2011, 10:11 PM
  3. binary tree
    By ryamz in forum New To Java
    Replies: 2
    Last Post: 08-12-2010, 03:45 AM
  4. Replies: 0
    Last Post: 04-04-2010, 08:40 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •