Hashing a Tree Structure

后端 未结 11 2005
渐次进展
渐次进展 2020-11-28 04:00

I\'ve just come across a scenario in my project where it I need to compare different tree objects for equality with already known instances, and have considered that some so

11条回答
  •  借酒劲吻你
    2020-11-28 04:24

    A simple enumeration (in any deterministic order) together with a hash function that depends when the node is visited should work.

    int hash(Node root) {
      ArrayList worklist = new ArrayList();
      worklist.add(root);
      int h = 0;
      int n = 0;
      while (!worklist.isEmpty()) {
        Node x = worklist.remove(worklist.size() - 1);
        worklist.addAll(x.children());
        h ^= place_hash(x.hash(), n);
        n++;
      }
      return h;
    }
    
    int place_hash(int hash, int place) {
      return (Integer.toString(hash) + "_" + Integer.toString(place)).hash();
    }
    

提交回复
热议问题