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?
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>re;
if (root == NULL)
return re;
vector<TreeNode*>que;
que.push_back(root);
bool f = true;
while (!que.empty())
{
if (f&&que.back()->left != NULL)
que.push_back(que.back()->left);
else
{
re.push_back(que.back()->val);
TreeNode*n = que.back(); que.pop_back();
if (n->right != NULL)
{
que.push_back(n->right);
f = true;
}
else
f = false;
}
}
return re;
}
};
accepted