/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
stack<TreeNode *> path;
vector<int> answer;
public:
vector<int> inorderTraversal(TreeNode* root) {
traverse(root);
return answer;
}
void traverse(TreeNode* cur){
while(cur || !path.empty()){
// first to the left
while(cur){
path.push(cur);
cur = cur -> left;
}
// left done , do cur
cur = path.top(); path.pop();
answer.push_back(cur->val);
// exploring right
cur = cur->right;
}
}
};
Step1. Initialize current as root
Step2. While current is not NULL
If current does not have left child
a. Add current’s value
b. Go to the right, i.e., current = current.right
Else
a. In current's left subtree, make current the right child of the rightmost node
b. Go to this left child, i.e., current = current.left
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> answer;
TreeNode *cur = root;
while(cur){
if(cur->left){
TreeNode* pre = cur -> left;
while(pre -> right) pre = pre -> right;
pre->right = cur;
TreeNode * temp = cur;
cur = cur -> left;
temp -> left = NULL;
}
else{
answer.push_back(cur->val);
cur = cur -> right;
}
}
return answer;
}
};