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

后端 未结 10 2270
刺人心
刺人心 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 12:07

    Here's a shorter version iluxa's original answer. It runs exactly the same node manipulation and printing steps, in exactly the same order — but in a simplified manner [1]:

    void traverse (Node n) {
      while (n) {
        Node next = n.left;
        if (next) {
          n.left = next.right;
          next.right = n;
          n = next;
        } else {
          print(n);
          n = n.right;
        }
      }
    }
    

    [1] Plus, it even works when the tree root node has no left child.

提交回复
热议问题