题目:
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].
递归方法遍历:
/**
* 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) {
vector<int> res;
if(!root)
return res;
inorder(root,res);
return res;
}
void inorder(TreeNode* root,vector<int> &res)
{
if(root)
{
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
}
};
非递归方法实现:
/**
* 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) {
stack<TreeNode*> s;
vector<int> res;
TreeNode* proot=root;
while(proot||!s.empty())
{
if(proot)
{
s.push(proot);
proot=proot->left;
}
else{
proot=s.top();
res.push_back(proot->val);
s.pop();
proot=proot->right;
}
}
return res;
}
};