递归方法:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* p,vector<int> &path)
{
if(p!=NULL){
inorder(p->left,path);
path.push_back(p->val);
inorder(p->right,path);
}
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> path;
inorder(root,path);
return path;
}
};
非递归方法(迭代方法):前中后遍历都使用栈,都可以将root先入,出栈序列有很多,不只是一种,要注意 这一点。
/**
* 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*> stk;
vector<int> path;
TreeNode* cur=root;
if(root==NULL) return path;
while(!stk.empty()||cur!=NULL){
while(cur){
stk.push(cur);
cur=cur->left;
}
cur=stk.top();
path.push_back(cur->val);
stk.pop();
cur=cur->right;
}
return path;
}
};