320x100
https://leetcode.com/problems/binary-tree-preorder-traversal/
이진 트리가 주어졌을 때, 전위 순회(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
'코딩테스트 준비 > leetcode' 카테고리의 다른 글
145. Binary Tree Postorder Traversal (0) | 2021.07.22 |
---|---|
1302. Deepest Leaves Sum [Medium] (0) | 2021.07.21 |
110. Balanced Binary Tree [Easy] (0) | 2021.07.21 |
543. Diameter of Binary Tree [Easy] (0) | 2021.07.20 |
94. Binary Tree Inorder Traversal (0) | 2021.07.19 |