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
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