Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created July 20, 2019 00:25
Show Gist options
  • Save zhangxiaomu01/19045770776fe6c937acc796041bbd8a to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/19045770776fe6c937acc796041bbd8a to your computer and use it in GitHub Desktop.
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