/**
* 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> out;
vector<int> preorderTraversal(TreeNode *root) {
if( !root )
return out;
out.push_back(root->val);
if( root->left )
{
preorderTraversal( root->left );
}
if( root->right )
{
preorderTraversal( root->right );
}
return out;
}
};
/** 非递归
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
class Solution {
public:
vector<int> out;
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> stack;
TreeNode * temp;
if( root == NULL )
return out;
temp = root;
while( temp != NULL || !stack.empty() )
{
while( temp != NULL )
{
out.push_back(temp->val);
stack.push(temp);
temp = temp->left;
}
if( !stack.empty() )
{
temp = stack.top();
stack.pop();
temp = temp->right;
}
}
return out;
}
};