Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 20, 2019 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/8f682787ca0bf7f0b8286b6ba2756b67 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/8f682787ca0bf7f0b8286b6ba2756b67 to your computer and use it in GitHub Desktop.
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> st;
TreeNode* pre = nullptr, *cur = root;
while(cur || !st.empty()){
while(cur){
st.push(cur);
cur = cur->left;
}
cur = st.top();
// pop immediately to avoid repetitively visit
st.pop();
res.push_back(cur->val);
if(cur->right && cur->right != pre){
cur = cur->right;
//We need to continue for the next loop in order
//to get the most left nodes to stack
continue;
}
pre = cur;
cur = nullptr;
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment