144. 二叉树的前序遍历
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void preorder(vector<int> &res,TreeNode* root){
if(root==nullptr){
return;
}
res.push_back(root->val);
preorder(res,root->left);
preorder(res,root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(res,root);
return res;
}
};