问题
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