如何在AVL树中查找重复值

时间:2015-04-26 22:16:15

标签: java avl-tree

private static void duplicate(AVLNode bTree)
{
   if(bTree != null)
   {
      if(bTree.left == bTree.right)
      {            
         duplicateNum += bTree.value + " ";
      }
   }
}

我试图编写一个方法,在AVL树中查找重复值并将它们显示到JTextField。我提供的代码中缺少什么?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

班级"节点"可能看起来像这样:

public class Node<K, V> {
    public Node left_child, right_child;
    public K key;
    public ArrayList<V> value; // Now each key holds a list of values

    // Make a subclass "NullNode" which indicates it isn't a node.
    // So that left/right childs can be ommitted by passing the NullNode (e.g for leaf nodes)
    public Node(Node left, Node right, K key, V value) {
        this.left_child = left;
        this.right_child = right;
        this.key = key;
        this.value.add(value);
    }

    // Get the node's values
    public ArrayList<V> values() {
        this.values;
    }

    // Are we a leaf node ? --> No
    public boolean leaf() {
        return false;
    }

    // Other needed procedures
}

public class NullNode extends Node<int, int> {
    public NullNode() {
         super(0, 0); // Just because we have to pass values
    }

    // We are a leaf node
    public boolean leaf() {
        return true;
    }
}

在对节点进行操作之前,您首先必须使用leaf()方法确保它不是叶节点。

请注意,这只是为了帮助您更进一步,它可以写得更清洁。