/**
-
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:
vector preorderTraversal(TreeNode root) {
vector vecResult;
preorderTraversalReal(vecResult,root);
return vecResult;
}
void preorderTraversalReal(vector&vecResult,TreeNode* root)
{
if(!root)return;
vecResult.push_back(root->val);
preorderTraversalReal(vecResult,root->left);
preorderTraversalReal(vecResult,root->right);}
};
前序遍历, 关键是要首先打印 当前节点。