코딩테스트 준비/leetcode

94. Binary Tree Inorder Traversal

MAKGA 2021. 7. 19. 21:18
320x100

https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/

 

Binary Tree Inorder 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

 

이진 트리를 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