Last active
August 29, 2015 13:55
-
-
Save sundeepblue/8743590 to your computer and use it in GitHub Desktop.
[tree] inorder traversal, concise iterative version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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