The question title does not mention the absence of a "parent" pointer in node. Although this is not required for BST, many binary tree implementations have a parent pointer. class Node {Node * on the left; Node * on the right; Node * parent; DATA data; };
This is so, drawing a diagram of a tree on paper and drawing with a pencil around a tree, rising and falling on both sides of the edges (during the descent you will remain from the edge, and when you rise, you will be on the right side). Basically, there are 4 states:
- SouthWest: You are on the left side of the edge, going from the parent to his left child.
- NorthEast: transition from left child back to parent
- SouthEast: Transitioning from Parent to Right Child
- NorthWest: transition from the right child to the parent object
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; } } }
Uri Mar 31 2018-11-11T00: 00Z
source share