Write a non-recursive traversal of a Binary Search Tree using constant space and O(n) run time

后端 未结 10 2256
刺人心
刺人心 2020-12-07 11:44

This is not homework, this is an interview question.

The catch here is that the algorithm should be constant space. I\'m pretty clueless on how to d

10条回答
  •  鱼传尺愫
    2020-12-07 11:53

    It's a binary search tree, so every node can be reached by a series of right/left decision. Describe that series as 0/1, least-significant bit to most-significant. So the function f(0) means "the node found by taking the right-hand branch until you find a leaf; f(1) means take one left and the rest right; f(2) -- that is, binary 010 -- means take a right, then a left, then rights until you find a leaf. Iterate f(n) starting at n=0 until you have hit every leaf. Not efficient (since you have to start at the top of the tree each time) but constant memory and linear time.

提交回复
热议问题