双指针法:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型vector
*/
void preorder(vector<int>&res, TreeNode* root)
{
if(root == NULL) return;
res.push_back(root->val);
preorder(res, root->left);
preorder(res, root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
// write code here
vector<int>res;
preorder(res,root);
return res;
}
};
栈
vector<int> preorderTraversal(TreeNode* root)
{
vector<int>res;
if(root == NULL) return res;
stack<TreeNode*>s;
s.push(root);
while(!s.empty())
{
TreeNode* node =s.top();
s.pop();
if(node != NULL)
res.push_back(node->val);//将栈顶元素,添加到数组中
else
continue;
if(node->right)
s.push(node->right);
if(node->left)
s.push(node->left);
}
return res;
}