Using Stack for Traversal: Void preOrder( Node* root ) { stack<Node*> stk; Node* cur = root; stk.push(cur); while ( !stk.empty() ) { Node* temp = stk.top(); stk.pop(); cout << temp->key << « «; if ( temp->right ) { stk.push(temp->right); } if ( temp->left ) { stk.push( temp->left); } } Void inOrder( Node* root ) { stack<Node*> stk; Node* cur = root; while ( cur || !stk.empty() ) { while ( cur ) { stk.push( cur ); cur = cur -> left; } cur = stk.top(); stk.pop(); cout << cur->key << « «; cur = cur->right; } } void postOrder( Node* root ) { stack<Node*> stk; Node* cur = root; while( cur || !stk.empty() ) { while ( cur ) { stk.push( cur ); cur=cur->left; } cur = stk.top(); if ( cur->right ) { cur=cur->right; } else { cout << cur->key << « «; stk.pop(); while ( stk.top()->right == cur ) { cur = stk.top(); cout << cur->key << « «; stk.pop(); } cur = stk.top()->right; } } }
以上为使用栈空间下的三种二叉树遍历。对于不使用栈的二叉树遍历,应当注意的是,后序遍历将新建一个节点,并将这个节点的左子树指向原来的root.
这样的记录其实很低效,别人估计也很难看懂这些代码,确实是这样的,毕竟是算法,procedure-oriented.所以必须要配图并且每一步自己跑一遍才能够真的懂,当一个简单案例你能够按步骤机械化操作得到结果,离程序也就不远了。
可以先先psudo code, 根据psudo code手动跑简单案例,这样比无头苍蝇似的想思路靠谱多了。
void preOrder( Node* root ) { Node* cur = root; while ( cur ) { if ( cur -> left == NULL ) { cur = cur->right; } else { Node* temp = cur->left; while ( temp->right && temp->right!=cur ) { temp = temp->right; } if ( temp->right == NULL ) { temp->right = cur; cout << cur->key; cur = cur -> left; } else { temp->right = NULL; cur = cur-> right; } } } } Void inOrder( Node* root ) { Node* cur = root; while ( cur ) { if ( cur ->left == NULL ) { cout << cur->key << « «; cur = cur->right; } else { Node* temp; temp = cur->left; while ( temp->right && temp->right != current ) { temp = temp->right; } if ( temp->right == NULL ) { temp->right = cur; cur = cur->left; } else { temp->right = NULL; cout << cur->key << « «; cur=cur->right; } } } } void reverse( Node* from, Node* to ) { Node* pre = from; Node* cur = from->right; Node* next = NULL; while ( true ) { if ( pre == to ) break; next = cur->right; cur -> right = pre; pre = cur; cur = next; } } void reversePrint( Node* from, Node* to ) { reverse( from, to ); Node* cur = from; while ( true ) { cout << cur->key << « «; if ( cur==to ) break; cur = cur->right; } reverse( to, from ); } Void postOrder( Node* root ) { Node* cur = root; while( cur ) { if ( cur -> left == NULL ) { cur = cur->right; } else { Node* temp = cur->left; while ( temp->right && temp->right != cur ) { temp = temp->right; } if ( temp->right == NULL ) { temp->right = cur; cur = cur->left; } else { reversePrint( cur->left, temp ); temp->right = NULL; cur = cur-> right; } } }