我需要一种方法recursive
/ non recursive
来打印从最大到最小的BST,
示例:
对于这棵树
提出了如何打印BST的答案
我想得到:25,20,16,15,10,9,8,6,4,3,2,1
我知道以相反的方式打印它的方式:(in order)
public void displaySmallToBig(Node root){ // inorder
if(root!=null){
displaySmallToBig(root.left);
System.out.print(" " + root.data);
displaySmallToBig(root.right);
}
}
将打印:1 2 3 4 4 6 8 9 10 15 16 20 25
先谢谢所有助手。
所有课程:
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;
}
}
答案 0 :(得分:4)
只需切换遍历顺序,然后先向右移动,然后向左移动:
public void displaySmallToBig(Node root) {
if (root != null) {
displaySmallToBig(root.right);
System.out.print(" " + root.data);
displaySmallToBig(root.left);
}
}
在这里演示: