思路:
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
Tree(root,res);
return res;
}
void Tree(TreeNode* root,vector<int>& res){
if(root){
res.push_back(root->val);
Tree(root->left,res);
Tree(root->right,res);
}
}
};
/**
* 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> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> tmp;
if(root == NULL) return {};
tmp.push(root);
while(!tmp.empty()){
TreeNode *p = tmp.top();
res.push_back(p->val);
tmp.pop();
if(p->right)tmp.push(p->right);
if(p->left)tmp.push(p->left);
}
return res;
}
};