I have a question. How to avoid that same tree like '2-4' appears multiple times. Can this situation lead to adding more than root nodes in the final result? Hope someone can answer. Thanks.

@RunRunCode
Yes in-order doesn't work as it mentioned in another thread.
However pre-oder works. When you construct the tree in pre-order, you know exactly where you start --- root. Then you will go to current node's children unless you meet two "null". As you can see, the tree constructed is unique.

The uniqueness of the serialized key is hard to either prove or negate without a careful analysis. I feel like it would work, but not confident indeed.

@dkonayuki I'm curious how you later find out it's unique. Because IMHO not being strictly pre-order doesn't necessary mean it's unique. Do I miss something here?

@lavender_sz sorry i meant that the key for the hashmap is the preorder sequence of the subtrees. the sequence which these nodes are visited by the function is postorder as you mentioned