652. Find Duplicate Subtrees

how to serialization

序列化: root + "," + s(root.left) + "," + s(root.right)

xx

xxx

因為對子樹做操作, so use postorder

postorder dfs, serialization with String

Can anyone explain how the first solution is O(n^2)? My understanding is that it pretty much does the same thing as second solution. Arent both O(n) - n being number of nodes in the tree?

Edit:

I understand now. Since strings are bring used, the concatenation takes O(n) time in each recursive call taking overall complexity to O(n2). https://stackoverflow.com/questions/15400508/string-concatenation-complexity-in-c-and-java

雖然 DFS 是 O(n), 但字串串接時用 String, 所以串接會是 O(n), 所以是 O(n^2)

use StringBuilder 應該就沒字串串接 O(n) 這問題, 但問題還是在於 hash , 如果字太長了 , hash 也會變成 從 O(1) -> O(n), (這題數量可以到

  • The number of the nodes in the tree will be in the range [1, 10^4]

), 所以是 dfs * String hash = O(n^2)

@shiyuluu is right. Concatenating in string isn't a main problem here. The problem is building hash from all seeing nodes fast.

If you want to build a hash from a string, you have to go through all the letters of that string. Each letter of this string is one node. Therefore, the first solution has a complexity of n ^ 2.

T: O(n^2)

S: O(n..larger)

postorder dfs + serialization + int id (識別符

Map<String key, global number> , when add new key, global number++

Map<global number, count

T: O(n)

S: O(n..larger)

We can improve this to O(n) by replacing full serializations with serial ids instead.

關鍵是 private int serialization, serialization 回來的是 int, 這樣就可以避免用 string 來做

serialization

所以雖然這也還是用 String, Integer , Map<String, Integer>

但因為 String key 會很短了, root.val + "int id" + "int id"

所以整個 serialization 過程就不會很久

these 3 line can to one line

Last updated

Was this helpful?