코딩테스트 준비/leetcode

144. Binary Tree Preorder Traversal [Easy]

MAKGA 2021. 7. 21. 23:12
320x100

https://leetcode.com/problems/binary-tree-preorder-traversal/

 

Binary Tree Preorder Traversal - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

이진 트리가 주어졌을 때, 전위 순회(preorder)로 값들을 vector에 모아 반환해주면 되는 문제다.

 

/**
 * 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<int> preorderTraversal(TreeNode* root) {
        if (root == nullptr) {
            return v;
        }
        
        v.push_back(root->val);
        
        if (root->left) {
            preorderTraversal(root->left);
        }
        
        if (root->right) {
            preorderTraversal(root->right);
        }
        
        return v;
    }
    
private:
    vector<int> v;
};

320x100