Leetcode 144 Binary Tree Preorder Traversal

2018-01-12 14:50:15 浏览数 (1)

Given a binary tree, return the preorder traversal of its nodes' values.

For example: Given binary tree {1,#,2,3},

代码语言:javascript复制
   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;
    }
};

0 人点赞