#include<iostream>
#include<vector>
#include<stack>
using namespace std;
// Definition for binary tree 先序遍历 根左右
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#if 0
class Solution { //me ok
public:
vector<int> v;
vector<int> preorderTraversal(TreeNode *root) {
if (root == NULL)
return v;
v.push_back((*root).val);
if((*root).left!=NULL)
preorderTraversal((*root).left);
if((*root).right!=NULL)
preorderTraversal((*root).right);
return v;
}
};
#endif
#if 0
class Solution {
public:
vector<int>res;
vector<int> preorderTraversal(TreeNode *root) {
if (root == NULL)
return res;
res.push_back(root->val);
if (root->left != NULL)
preorderTraversal(root->left);
if (root->right != NULL)
preorderTraversal(root->right);
return res;
}
};
#endif
#if 0 //我非迭代 错误
class Solution {
public:
vector<int> v;
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode *node = s.top();
s.pop();
if (node != NULL)
v.push_back(node->val);
if (node->left != NULL)
s.push(node->left);
if (node->right != NULL)
s.push(node->right);
}
}
};
#endif
#if 1 //我非迭代
class Solution {
public:
vector<int> v;
stack<TreeNode*> s;
vector<int> preorderTraversal(TreeNode *root) {
if (root ==NULL) {
return v;
}
s.push(root);
while (!s.empty()) {
TreeNode *node = s.top();
s.pop();
v.push_back(node->val);
if (node->right != NULL)
s.push(node->right);
if (node->left != NULL)
s.push(node->left);
}
return v;
}
};
#endif