Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
生成二叉树时,每次需要随机选择一个节点作为父节点。这需要维护一个集合,支持加入元素和随机删除一个元素。
原代码中,使用 Python 的
set
维护这个集合,每次把set
转换成tuple
再用random.choice()
选择元素,这样的复杂度是单次 O(n) 的,在生成较大的二叉树时无法承受。为了优化这个复杂度,我尝试把它修改成
set.pop()
,但这个方法返回的元素不是随机的。后来我参考 这个回答,用list
实现了单次 O(1) 的复杂度,实测有一定的性能提升。修改后通过了
unit_test.py
的单元测试(环境:Python 2.7.17, Python 3.6.9; Ubuntu 18.04)。