Binary Tree Inorder Traversal:
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 binary tree
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<TreeNode* > st;
vector<int> order;
TreeNode* p=root;
while(p!=NULL||!st.empty())
{
while(p)
{
st.push(p);
p=p->left;
}
if ( !st.empty())
{
p=st.top();
st.pop();
order.push_back(p->val);
p=p->right;
}
}
return order;
}
};