Created
July 20, 2019 00:27
-
-
Save zhangxiaomu01/8f682787ca0bf7f0b8286b6ba2756b67 to your computer and use it in GitHub Desktop.
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; | |
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