//递归法:
/**
* 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:
void pTra(TreeNode* root, vector<int> &vec) {
if (root == NULL) return;
vec.insert(vec.end(), root->val);
pTra(root->left, vec);
pTra(root->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
pTra(root, result);
return result;
}
};
//非递归法:
/**
* 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> result;
stack<TreeNode *> rootStack;
rootStack.push(root);
TreeNode* curNode;
while(!rootStack.empty()) {
curNode = rootStack.top();
rootStack.pop();
if (curNode == NULL)
continue;
result.insert(result.end(), curNode->val);
rootStack.push(curNode->right);
rootStack.push(curNode->left);
}
return result;
}
};