[英]A method to print a binary search tree (BST) from the largest element to the smallest
我認為我必須修改遍歷之一。 我嘗試將打印的內容從最小的修改為最大
private void printTree(BinaryTreeNode t) {
if (t != null) {
printTree(t.llink);
System.out.print(" " + t.info);
printTree(t.rlink);
}
}
但這沒有用。 我仍然停留在下一步應該嘗試的地方。 這是我正在使用的二進制搜索樹:
public class BinarySearchTree extends BinaryTree {
//Default constructor.
//Postcondition: root = null;
public BinarySearchTree() {
super();
}
//Copy constructor.
public BinarySearchTree(BinarySearchTree otherTree) {
super(otherTree);
}
public class BinaryTree {
//Definition of the node
protected class BinaryTreeNode {
DataElement info;
BinaryTreeNode llink;
public DataElement getInfo() {
return info;
}
public BinaryTreeNode getLlink() {
return llink;
}
public BinaryTreeNode getRlink() {
return rlink;
}
BinaryTreeNode rlink;
}
protected BinaryTreeNode root;
//Default constructor
//Postcondition: root = null;
public BinaryTree() {
root = null;
}
//Copy constructor
public BinaryTree(BinaryTree otherTree) {
if (otherTree.root == null) //otherTree is empty.
{
root = null;
}
else {
root = copy(otherTree.root);
}
}
public BinaryTreeNode getRoot() {
return root;
}
您發布的代碼看起來可以從最小到最大排序。
如果您想進行其他排序,那么以下代碼應該可以工作:
private void printTree(BinaryTreeNode t) {
if (t != null) {
printTree(t.rlink);
System.out.print(" " + t.info);
printTree(t.llink);
}
}
您所要做的全部交換llink和rlink。 要從大到小打印樹,可以使用樹遍歷方法之一。 例如,適合這種情況的一種是有序遍歷,因為它按值從最小到最大打印樹。 您所要做的只是以下幾點:
if(t!=null){
printTree(t.rlink);
System.out.print(" " + t.info);
printTree(t.llink);
}
那應該從最大到最小打印它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.