Print Binary search tree from biggest number to smallest using Java

时光怂恿深爱的人放手 提交于 2019-12-02 20:17:22

问题


I need a way, recursive / non recursive to print BST from biggest to smallest number, Example : for this tree came threw the answer of how to print BST

I would like to get : 25,20,16,15,10,9,8,6,4,3,2,1

I know the way to print it opposite way : (in order)

public void displaySmallToBig(Node root){ // inorder
   if(root!=null){
       displaySmallToBig(root.left);
       System.out.print(" " + root.data);
       displaySmallToBig(root.right);
   }
}

Will print : 1 2 3 4 4 6 8 9 10 15 16 20 25

Thanks in advance 2 all the helpers.

all the class :

package com.company;

public class BinarySearchTree {
    public static  Node root;
    public BinarySearchTree(){
        this.root = null;
    }


    public void displaySmallToBig(Node root){ // inorder
        if(root!=null){
            displaySmallToBig(root.left);
            System.out.print(" " + root.data);
            displaySmallToBig(root.right);
        }
    }

    public void displayBigToSmall(Node root){
        if(root!=null){
            displaySmallToBig(root.right);
            System.out.print(" " + root.data);
            displaySmallToBig(root.left);
        }
    }

    public static void main(String arg[]){
        BinarySearchTree b = new BinarySearchTree();
        b.insert(3);
        b.insert(8);
        b.insert(1);
        b.insert(4);
        b.insert(6);
        b.insert(2);
        b.insert(10);
        b.insert(9);
        b.insert(20);
        b.insert(25);
        b.insert(15);
        b.insert(16);

        System.out.println("Original Tree : ");

        System.out.println("displaySmallToBig");
        b.displaySmallToBig(b.root);
        System.out.println("");
        System.out.println("displayBigToSmall");
        b.displayBigToSmall(b.root);
    }
}

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

回答1:


Just switch the order of traversal such that you traverse right first, then left:

public void displaySmallToBig(Node root) {
    if (root != null) {
        displaySmallToBig(root.right);
        System.out.print(" " + root.data);
        displaySmallToBig(root.left);
    }
}

Demo here:

Rextester



来源:https://stackoverflow.com/questions/44181981/print-binary-search-tree-from-biggest-number-to-smallest-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!