因此,我们的想法是制作一个双端优先级队列。到目前为止,我已经使用了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);
}
}
}
}
您应该能够修改您的TreeNode.getMost(TreeNoden)和TreeNode.get-Least(Treenoden),类似于以下内容:
public class TreeNode{
// Also, your parameter here seems to be superfluous.
public TreeNode getMost(TreeNode n) {
if (n.right == null) {
n.root.right = null;
return n;
}
return n.getMost(n);
}
}
Get least应该能够以类似的方式进行修改,但显然使用left而不是right。