Leetcode 144. Binary Tree Preorder Traversal二叉树前序遍历

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;
    }
};

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/87825298