You maintain a merchant menu as a rooted tree. Each node represents a menu item/category and has:
key
(string, unique among siblings)
value
(integer)
children
(0..k child nodes)
When a merchant sends a new menu tree, you want to count how many nodes have changed compared to the existing menu.
A node is considered changed if any of the following is true:
key
), but its
value
differs.
Important: If a node with the same key appears under a different parent in the new tree, treat this as removal of the old node (and its subtree) plus addition of the new node (and its subtree).
Given the roots of the old and new trees, return the number of changed nodes.
Old tree:
New tree:
Output: 4
Explanation: b, d, e are removed (3 changes) and f value changes from 6 to 66 (1 change).
Old tree:
New tree:
Output: 5
Explanation: f is added (1). Subtree rooted at c is removed (c and its child g: 2). Subtree rooted at h is added (h and its child g: 2). Total = 1 + 2 + 2 = 5.
2 * 10^5
.
key
is unique among siblings (so children can be matched by
key
under the same parent).
Design an algorithm to compute the count efficiently.