Write a non-recursive traversal of a Binary Search

2019-01-16 03:14发布

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 do this without a stack, I'd post what I've written using a stack, but it's not relevant anyway.

Here's what I've tried: I attempted to do a pre-order traversal and I got to the left-most node, but I'm stuck there. I don't know how to "recurse" back up without a stack/parent pointer.

Any help would be appreciated.

(I'm tagging it as Java since that's what I'm comfortable using, but it's pretty language agnostic as is apparent.)

10条回答
Root(大扎)
2楼-- · 2019-01-16 03:54

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-16 03:55

The title of the question doesn't mention the lack of a "parent" pointer in the node. Although it isn't necessarily required for BST, many binary tree implementations do have a parent pointer. class Node { Node* left; Node* right; Node* parent; DATA data; };

It this is the case, imaging a diagram of the tree on paper, and draw with a pencil around the tree, going up and down, from both sides of the edges (when going down, you'll be left of the edge, and when going up, you'll be on the right side). Basically, there are 4 states:

  1. SouthWest: You are on the left side of the edge, going from the parent its left child
  2. NorthEast: Going from a left child, back to its parent
  3. SouthEast: Going from a parent to a right child
  4. NorthWest: Going from a right child, back to its parent

Traverse( Node* node )
{
    enum DIRECTION {SW, NE, SE, NW};
    DIRECTION direction=SW;

    while( node )
    {
        // first, output the node data, if I'm on my way down:
        if( direction==SE or direction==SW ) {
            out_stream << node->data;
        }

        switch( direction ) {
        case SW:                
            if( node->left ) {
                // if we have a left child, keep going down left
                node = node->left;
            }
            else if( node->right ) {
                // we don't have a left child, go right
                node = node->right;
                DIRECTION = SE;
            }
            else {
                // no children, go up.
                DIRECTION = NE;
            }
            break;
        case SE:
            if( node->left ) {
                DIRECTION = SW;
                node = node->left;
            }
            else if( node->right ) {
                node = node->right;
            }
            else {
                DIRECTION = NW;
            }
            break;
        case NE:
            if( node->right ) {
                // take a u-turn back to the right node
                node = node->right;
                DIRECTION = SE;
            }
            else {
                node = node->parent;
            }
            break;
        case NW:
            node = node->parent;
            break;
        }
    }
}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-16 03:56

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;
            }
        }
查看更多
Ridiculous、
5楼-- · 2019-01-16 04:00

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.

查看更多
欢心
6楼-- · 2019-01-16 04:04

Accepted answer needs the following change otherwise it will not print the tree where the BST only has one node

if (current == NULL && root != NULL)
   print(root);
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-16 04:05

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;
}
查看更多
登录 后发表回答