Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root == nullptr) return res;
//Maintain a variable for current value. For inorder traversal,
//we need to push left nodes to our stack, then add the value to res.
TreeNode* cur = root;
while(cur || !st.empty()){
if(cur!= nullptr){
st.push(cur);
cur = cur->left;
}
else{
//We need to update cur. because currentlt it's nullptr
cur = st.top();
res.push_back(cur->val);
st.pop();
cur = cur->right;
}
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment