250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code c++)Binary Tree Preorder Traversal 본문
728x90
반응형
144. Binary Tree Preorder Traversal
Easy
252693Add to ListShare
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3] Output: [1,2,3]
Example 2:
Input: root = [] Output: []
Example 3:
Input: root = [1] Output: [1]
Example 4:
Input: root = [1,2] Output: [1,2]
Example 5:
Input: root = [1,null,2] Output: [1,2]
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
이진 트리의 전위 순회를 통해 값을 answer 벡터에 저장하는 과정이다.
트리의 순회 중 가장 기본적인 방법이다.
/**
* 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:
void preorder(TreeNode * node, vector<int> &answer){
answer.push_back(node->val);
if(node->left != NULL){
preorder(node->left, answer);
}
if(node->right != NULL){
preorder(node->right, answer);
}
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> answer;
if(root != NULL){
preorder(root, answer);
}
return answer;
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Min Stack (0) | 2021.07.19 |
---|---|
(Leet Code c++)Binary Tree Postorder Traversal (0) | 2021.07.19 |
(Leet Code c++)Linked List Cycle (0) | 2021.07.17 |
(Leet Code c++)Single Number (0) | 2021.07.17 |
(Leet Code c++)Valid Palindrome (0) | 2021.07.16 |