递归怎么写才规范?根左右---根就是对数据的处理。前中后就是根的位置不同。
/**
* 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 dfs(TreeNode* root, vector<int>& result) {
TreeNode* cur = root;
if (cur == nullptr) return ;
result.push_back(cur->val);
dfs(cur->left, result);
dfs(cur->right, result);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
dfs(root, result);
return result;
}
};