一、题目
二、代码
/**
* 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 tree_for_each_recursive(TreeNode* cur,vector<int>& result) //二叉树的递归遍历
{
if(cur==nullptr) return;
result.push_back(cur->val);
tree_for_each_recursive(cur->left,result);
tree_for_each_recursive(cur->right,result);
};
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> return_vector;
tree_for_each_recursive(root,return_vector);
return return_vector;
}
};