class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
digui(res,root);
return res;
}
void digui(vector<int> & res,TreeNode * root){
if(root==NULL) return;
if(root) res.push_back(root->val);
digui(res,root->left);
digui(res,root->right);
return;
}
};
非递归的方法,使用到栈:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<pair<TreeNode*,bool>> s;
s.push(make_pair(root,false));
while(!s.empty()){
pair<TreeNode *,bool> tmp = s.top();
s.pop();
if(tmp.second) res.push_back(tmp.first->val);
else{//这里犯了一个错误,只有当top的second等于false的时候,左右孩子才压栈
if(tmp.first->right) s.push(make_pair(tmp.first->right,false));
if(tmp.first->left) s.push(make_pair(tmp.first->left,false));
s.push(make_pair(tmp.first,true));
}
}
return res;
}
};