Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
/**
* 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> v;
if(root==NULL)
return v;
stack<TreeNode*> s;
s.push(root);
while(!s.empty())
{
while(s.top()->left!=NULL)
s.push(s.top()->left);
TreeNode* node=s.top();
v.push_back(node->val);
while(!s.empty())
{
s.pop();
if(node->right!=NULL)
{
//s.pop();
s.push(node->right);
break;
}
else if(!s.empty())
{
node=s.top();
v.push_back(node->val);
}
}
}
return v;
}
};