Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
2
/
3
return [1,2,3]
.
二叉树先序遍历,easy
代码语言:javascript复制/**
* 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 dfs(TreeNode* root, vector<int> &res)
{
res.push_back(root->val);
if(root->left) dfs(root->left, res);
if(root->right) dfs(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root) dfs(root, res);
return res;
}
};