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 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> res;
inorderhelp(root,res);
return res; }
void inorderhelp(TreeNode* root,vector<int> &res)
{
if(root==NULL)
return;
inorderhelp(root->left,res);
res.push_back(root->val);
inorderhelp(root->right,res);
return;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root)
{
vector<int> res;
stack<pair<TreeNode* ,int>> s;
s.push(make_pair(root,));
while(!s.empty())
{
TreeNode *now=s.top().first;
if(now==NULL)
s.pop();
else{
switch(s.top().second++)
{
case :
s.push(make_pair(now->left,));
break;
case :
res.push_back(now->val); break;
default:
s.pop();
s.push(make_pair(now->right,));
break;
} }
}
return res;
} };
上一篇:直接用nose进行django项目测试并输出html报告


下一篇:asp.net正则表达式