Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
题目链接:https://leetcode.com/problems/binary-tree-preorder-traversal/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void pre_order(TreeNode* root,vector<int>&res)
{
if(root)
{
res.emplace_back(root->val);
pre_order(root->left,res);
pre_order(root->right,res);
}
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
pre_order(root,res);
return res;
}
};