넘치게 채우기

[LeetCode] 94. Binary Tree Inorder Traversal 본문

PS/LeetCode

[LeetCode] 94. Binary Tree Inorder Traversal

riveroverflow 2023. 12. 9. 13:50
728x90
반응형

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

 

Binary Tree Inorder Traversal - LeetCode

Can you solve this real interview question? Binary Tree Inorder Traversal - Given the root of a binary tree, return the inorder traversal of its nodes' values.   Example 1: [https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg] Input: root = [1,nu

leetcode.com

leetcode - Binary Tree Inorder Traversal

문제 유형 : 순회, DFS, 트리

문제 난이도 : Easy

9일연속 쉬움문제라니.. 얼마나 어려운게 기다리고 있을까?

 

문제

Given the root of a binary tree, return the inorder traversal of its nodes' values.

이진트리의 루트가 주어진다. 중위 순회로 노드들의 값을 반환하라.

 

풀이

간단하게도, 중위 순회한 값을 반환해주면 된다!

(왼쪽 서브트리) + (현재 루트의 값) + (오른쪽 서브트리)를 이어주면 된다!

 

코드

C++

/**
 * 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> inorderTraversal(TreeNode* root) {
        if(root == nullptr) return {};
        auto leftTree = inorderTraversal(root -> left);
        auto rightTree = inorderTraversal(root -> right);
        leftTree.insert(leftTree.end(), root -> val);
        leftTree.insert(leftTree.end(), rightTree.begin(), rightTree.end());

        return leftTree;
    }
};
728x90
반응형