0

I am working on BST and right now trying tree traversal.My inorder traversal output is coming correct by pre order and post order output is not coming correct. My code is

public class binarytree {

static class Node{

    Node left;
    Node right;
    int value;

    public Node(int value)
        {
        this.value = value;
        this.left = null;
        this.right = null;
        }
    }

public void creatBST()
    {
    Node root = new Node(4);
    System.out.println("Binary Search tree with root = "+ root.value);
    insert(root,1);
    insert(root,2);
    insert(root,3);
    insert(root,6);
    insert(root,5);
    insert(root,7);
    //insert(root,1);
    System.out.println("Binary Search Tree in In Order Traversal is:");
    printInOrder(root);

    System.out.println("Binary Search Tree in Pre Order Traversal is:");
    printPreOrder(root);

    System.out.println("Binary Search Tree in Post Order Traversal is:");
    printPostOrder(root);
    }

public void insert(Node node, int value)
    {
    if(value < node.value)
        {
        if(node.left != null)
            {
            insert(node.left, value);       
            }
        else
            node.left = new Node(value);
        }
    else if(value > node.value)
        {
        if(node.right != null)
            {
            insert(node.right, value);
            }
        else
            node.right = new Node(value);
        }
    }


public void printInOrder(Node node)                           //In Order Traversal
    {
    //Node node = this;
    if(node != null)
        {
        //System.out.println("Binary Search Tree in In Order Traversal is:");
        printInOrder(node.left);
        System.out.println(node.value);
        printInOrder(node.right);
        }
    }

public void printPreOrder(Node node)                      // Pre Order Traversal
{
//Node node = this;
if(node != null)
    {
    //System.out.println("Binary Search Tree in In Order Traversal is:");
    System.out.println(node.value);
    printInOrder(node.left);

    printInOrder(node.right);
    }
}

public void printPostOrder(Node node)                   // Post Order traversal
{
//Node node = this;
if(node != null)
    {
    //System.out.println("Binary Search Tree in In Order Traversal is:");

    printInOrder(node.left);

    printInOrder(node.right);
    System.out.println(node.value);
    }
}




public static void main(String args [])
    {
    binarytree obj = new binarytree();
    obj.creatBST();
    //obj.printInOrder();
    }
}

In preorder the output that I am getting is

4-1-2-3-5-6-7

while shouldn't it be

4-1-2-3-6-5-7

. Similarly for post order output is

1-2-3-5-6-7-4

while it should be

3-2-1-5-7-6-4

.

Don't know where I am getting wrong.

4

1 回答 1

1

您的预购和后购都仅在第一次通话中进行预购/后购。之后,您按顺序移动。

尝试将您的函数更改为递归调用自己而不是按顺序调用。

于 2014-02-01T03:18:03.597 回答