Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
recursive solution:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
myIOT(result,root);
return result;
}
void myIOT(vector<int> & result, TreeNode* root){
if(root == NULL) return;
myIOT(result,root->left);
result.push_back(root->val);
myIOT(result,root->right);
}
};
iterative way:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> myStack;
myStack.push(root);
while(!myStack.empty()){
TreeNode * now = myStack.top();
while(now != NULL){
now = now->left;
myStack.push(now);
}
myStack.pop();
if(!myStack.empty()){
now = myStack.top();
myStack.pop();
myStack.push(now->right);
result.push_back(now->val);
}
}
// myIOT(result,root);
return result;
}
// void myIOT(vector<int> & result, TreeNode* root){
// if(root == NULL) return;
// myIOT(result,root->left);
// result.push_back(root->val);
// myIOT(result,root->right);
// }
};