Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Last active August 29, 2015 13:55
Show Gist options
  • Save sundeepblue/8743590 to your computer and use it in GitHub Desktop.
Save sundeepblue/8743590 to your computer and use it in GitHub Desktop.
[tree] inorder traversal, concise iterative version
void in_order(TreeNode *root) {
if(!root) return;
stack<TreeNode*> s;
TreeNode *curr = root;
//s.push(curr);
while(true) {
if(curr) {
s.push(curr);
curr = curr->left;
}
else {
if(s.empty()) break;
curr = s.top(); s.pop();
visit(curr);
curr = curr->right;
}
}
}
// better version
void inorder_traversal(TreeNode *root) {
if(!root) return;
stack<TreeNode*> s;
TreeNode *cur = root; // gist, use a temp variable cur to traverse. Do not push cur into stack now.
while(1) {
while(cur) {
s.push(cur); // all elements in stack are non-NULL.
cur = cur->left;
}
if(s.empty()) break;
cur = s.top();
s.pop();
visit(cur);
cur = cur->right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment