320x100
https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/
이진 트리를 input으로 받아 중위 순회로 vector에 값을 채워 반환하는 문제.
중위 순회는 left, root, right순으로 방문하는 방법이다.
/**
* 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 inorderTraversal(vector<int>& nums, TreeNode* node)
{
if (node == nullptr) {
return;
}
if (node->left != nullptr) {
inorderTraversal(nums, node->left);
}
nums.push_back(node->val);
if (node->right != nullptr) {
inorderTraversal(nums, node->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
inorderTraversal(ret, root);
return ret;
}
};
320x100
'코딩테스트 준비 > leetcode' 카테고리의 다른 글
110. Balanced Binary Tree [Easy] (0) | 2021.07.21 |
---|---|
543. Diameter of Binary Tree [Easy] (0) | 2021.07.20 |
108. Convert Sorted Array to Binary Search Tree (0) | 2021.07.18 |
111. Minimum Depth of Binary Tree (0) | 2021.07.17 |
98. Validate Binary Search Tree [Medium] (0) | 2021.06.18 |