【发布时间】:2015-11-23 12:28:59
【问题描述】:
因此,我的想法是创建一个双端优先级队列,到目前为止,我已经使用 2 个链接列表获得了一个树状结构,我必须坚持使用它且不对其进行任何更改的界面。我遇到的问题是我必须创建两个名为 getMost 和 getLeast 的方法,它们获取最多或最少的节点,然后使该节点为空。但事实证明,这两种方法很难实现。你会怎么做呢?
我尝试过使用递归,但这很困难,因为我必须通过 tree.root 来选择树,但是将 tree.root 传递给递归方法总是从 tree.root 开始
我还尝试了我在 inspectLeast() 和 inspectMost() 中编写的内容,但 Java 通过值而不是引用传递。有什么建议吗?
P.S 不允许使用 java 集合或 java util 中的任何内容。
public class PAS43DPQ implements DPQ
{
//this is the tree
TreeNode tree = new TreeNode();
//this is for the size of the array
int size = 0;
@Override
public Comparable inspectLeast() {
return tree.inspectLeast(tree.root);
}
@Override
public Comparable inspectMost() {
return tree.inspectMost(tree.root);
}
@Override
public void add(Comparable c)
{
tree.add(c);
size++;
}
@Override
public Comparable getLeast() {
if (tree.root != null){
}
return getLeast();
}
@Override
public Comparable getMost(){
Comparable most = getMost();
return most;
}
@Override
public boolean isEmpty() {
return (size > 0)?true:false;
}
@Override
public int size() {
return this.size;
}
class TreeNode{
private Comparable value;
private TreeNode left, right, root;
//constructors
public TreeNode() {}
public TreeNode(TreeNode t) {
this.value = t.value;
this.left = t.left;
this.right = t.right;
this.root = t.root;
}
public TreeNode(Comparable c) {
this.value = (int) c;
}
public void add(Comparable input){
if(root == null){
root = new TreeNode(input);
return;
} else {
insert(root, input);
}
}
public Comparable inspectLeast(TreeNode n){
if (n == null)
return null;
if (n.left == null){
TreeNode least = n;
return least.value;
}
return inspectLeast(n.left);
}
public Comparable inspectMost(TreeNode n){
if (n == null)
return null;
if (n.right == null){
TreeNode most = n;
return most.value;
}
return inspectMost(n.right);
}
public Comparable getMost(TreeNode n){
if(n.right == null)
return n.value;
return tree.getMost(right);
}
public void insert(TreeNode n, Comparable input){
if(input.compareTo(n.value) >= 0){
if (n.right == null) {
n.right = new TreeNode(input);
return;
}
else
insert(n.right, input);
}
if(input.compareTo(n.value) < 0){
if(n.left == null) {
n.left = new TreeNode(input);
return;
}
else
insert(n.left, input);
}
}
}
}
【问题讨论】:
标签: java linked-list priority-queue