In-order traversal complexity in a binary search tree (using iterators)?

╄→尐↘猪︶ㄣ 提交于 2019-12-03 03:25:58

Yes, the amortized cost is indeed O(1) per iteration, for a any tree.

The proof is based on the number of times you "visit" each node.
Leaves are visited only once. None leaves are visited at most 3 times:

  1. when going from the parent to the node itself.
  2. when coming back from the left subtree
  3. when coming back from the right subtree

There are no more visits to any nodes, thus if we sum the number of visits of each node, we get a number that is smaller then 3n, so the total number of visits of all nodes combined is O(n), which gives us O(1) per step amortized.

(Note since in a full tree there are n/2 leaves, we are getting the 2n you were encountering, I believe one can show that the sum of visits will be smaller then 2n for any tree, but this "optimization" is out of scope here IMO).


The worst case per step is O(h), which is O(logn) in a balanced tree, but might be O(n) in some cases.


P.S. I have no idea how Red-Black trees are implemented in C++, but if your tree data structure contains a parent field from each node, it can replace the recursive stack and allow O(1) space consumption. (This is of course "cheating" because storing n such fields is O(n) itself).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!