【问题标题】:Binary search tree and in-order traversal二叉搜索树和中序遍历
【发布时间】:2015-02-16 08:16:16
【问题描述】:

我正在尝试在 Java 中快速实现二叉搜索树。具有按顺序遍历方法的最佳使用类是什么? (我听说过 TreeMap 类。但看起来该类不包含任何按顺序遍历的方法)。

【问题讨论】:

标签: java binary-search-tree


【解决方案1】:

使用LinkedHashMap按插入顺序遍历或TreeMap按比较顺序遍历 http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

【讨论】:

  • 你能告诉我更多关于比较顺序的信息吗?
  • 通过比较它们对键进行排序 - 使用键类的 compareTo 方法 - 或者您可以在地图创建时间指定比较器
【解决方案2】:

您总是可以创建自己的类,并使用该类实现算法。

public class Node {
    Node leftChild;
    Node rightChild;
    int parent;

    Node(int parent) {
        this.parent = parent;
    }
}

然后实现二叉搜索树类。这个速度很快,但它是为了给你一个想法。

public class BSTree {
Node root;

BSTree() {
    root = null;
}

public void insert(Node node, int value) {
    if (value >= node.parent) {
        if (!(node.rightChild == null)) {
            insert(node.rightChild, value);
        } else {
            node.rightChild = new Node(value);
        }
    } else if (value < node.parent) {
        if (!(node.leftChild == null)) {
            insert(node.leftChild, value);
        } else {
            node.leftChild = new Node(value);
        }
    } else {
        root = new Node(value);
    }
}


public boolean delete(Node node, int value) {
    if (root == null) {
        return false;
    } else if (value > root.parent) {
        return delete(root.rightChild, value);
    } else if (value < root.parent) {
        return delete(root.leftChild, value);
    } else {
        if (root.leftChild == null && root.rightChild == null) {
            root = null;
            return true;
        } else if (root.leftChild == null && root.rightChild != null) {
            root = root.rightChild;
            return true;
        } else if (root.leftChild != null && root.rightChild == null) {
            root = root.leftChild;
            return true;
        } else {
                            Node minRight = minNode(root.rightChild);
                            root = minRight;
                            delete(minRight, minRight.parent);
                            return true;
        }
    }
}

public Node minNode(Node node) {
    if (node.leftChild == null) {
        return node;
    } else {
        return minNode(node.leftChild);
    }
}
}

【讨论】:

    【解决方案3】:

    TreeSet 类可能是你想要的

    class Node implements Comparable<Node>;   // implements your Node class
    TreeSet<Node> set = new TreeSet<Node>();
    
    // after adding a bunch of nodes into set
    Iterator<Node> it = set.iterator();
    while(it.hasNext()){
        Node current = it.next();
        System.out.println(current); // operate on current node
    }
    
    Node first = set.first();    // smallest element in set
    Node second = set.ceiling(first);    // the successor method
    

    【讨论】:

      猜你喜欢
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多