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

后端 未结 10 2223
刺人心
刺人心 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:59

    It's a a search tree, so you can always get the next key/entry

    You need smth like (I didn't test the code, but it's as simple as it gets)

    java.util.NavigableMap<K, V> map=...
    for (Entry<K, V> e = map.firstEntry(); e!=null; e = map.higherEntry(e.getKey())) {
      process(e)
    }
    

    for clarity this is higherEntry, so it's not recursive. There you have it :)

    final Entry<K,V> getHigherEntry(K key) {
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = compare(key, p.key);
            if (cmp < 0) {
                if (p.left != null)
                    p = p.left;
                else
                    return p;
            } else {
                if (p.right != null) {
                    p = p.right;
                } else {
                    Entry<K,V> parent = p.parent;
                    Entry<K,V> ch = p;
                    while (parent != null && ch == parent.right) {
                        ch = parent;
                        parent = parent.parent;
                    }
                    return parent;
                }
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-12-07 11:59

    minor special case for iluxa's answer above

    if(current== null)
            {
                current = root;
                parent = current.Right;
                if(parent != null)
                {
                    current.Right = parent.Left;
                    parent.Left = current;
                }
            }
    
    0 讨论(0)
  • 2020-12-07 12:01

    If you are using a downwards pointer based tree and don't have a parent pointer or some other memory it is impossible to traverse in constant space.

    It is possible if your binary tree is in an array instead of a pointer-based object structure. But then you can access any node directly. Which is a kind of cheating ;-)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题