Untitled

 avatar
unknown
java
5 months ago
1.4 kB
3
Indexable
public static int calculateChanges(Node existingRoot, Node newRoot) {
        // Build maps for both trees
        Map<String, Node> existingMap = buildNodeMap(existingRoot);
        Map<String, Node> newMap = buildNodeMap(newRoot);

        // Track changes
        List<String> added = new ArrayList<>();
        List<String> deleted = new ArrayList<>();
        List<String> updated = new ArrayList<>();

        // Detect added and updated nodes
        for (Map.Entry<String, Node> entry : newMap.entrySet()) {
            String key = entry.getKey();
            Node newNode = entry.getValue();
            if (!existingMap.containsKey(key)) {
                added.add(key);
            } else {
                Node existingNode = existingMap.get(key);
                if (existingNode.value != newNode.value) {
                    updated.add(key);
                }
            }
        }

        // Detect deleted nodes
        for (String key : existingMap.keySet()) {
            if (!newMap.containsKey(key)) {
                deleted.add(key);
            }
        }
        
         private static void buildNodeMapHelper(Node node, Map<String, Node> nodeMap) {
        if (node == null) return;
        nodeMap.put(node.key, node);
        for (Node child : node.children) {
            buildNodeMapHelper(child, nodeMap);
        }
    }
        
        
}
Editor is loading...
Leave a Comment