[英]Print Binary search tree from biggest number to smallest using Java
I need a way, recursive
/ non recursive
to print BST from biggest to smallest number, Example : for this tree 我需要一种
recursive
/ non recursive
来从最大数到最小数打印BST,例如:对于这棵树 came threw the answer of how to print BST
来了如何打印BST的答案
I would like to get : 25,20,16,15,10,9,8,6,4,3,2,1
我想得到:
25,20,16,15,10,9,8,6,4,3,2,1
I know the way to print it opposite way : (in order)
我知道以相反的方式打印它的方法:(
(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
将打印:
1 2 3 4 4 6 8 9 10 15 16 20 25
Thanks in advance 2 all the helpers. 在此先感谢2所有帮助者。
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;
}
}
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: 演示在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.