递归:
/**
* 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 preorder(TreeNode *root,vector<int> &path)
{
if(root!=NULL)
{
path.push_back(root->val);
preorder(root->left,path);
preorder(root->right,path);
}
}
vector<int> preorderTraversal(TreeNode *root) {
vector<int> path;
preorder(root,path);
return path;
}
};
非递归 :
/**
* 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> preorderTraversal(TreeNode *root) {
vector<int> path;
stack<TreeNode*> stk;
if(root==NULL) return path;
stk.push(root);
TreeNode *cur=NULL;
while(!stk.empty())
{
cur=stk.top();
path.push_back(cur->val);
stk.pop();
if(cur->right!=NULL){
stk.push(cur->right);
cur->right==NULL;
}
if(cur->left!=NULL){
stk.push(cur->left);
cur->left=NULL;
}
}
}
};