문제

 

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

 

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

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

 

Example 1:

Input Output
root = [1,null,2,3] [1,3,2]

Example 2:

Input Output
root = [] []

Example 3:

Input Output
root = [1] [1]

 

 

문제풀이 코드

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        result = []
        def inOrder(root):
            if not root:
                return
            inOrder(root.left)
            result.append(root.val)
            inOrder(root.right)
        inOrder(root)
        
        return result

기본적인 트리 순회 문제 (중위 순회)

 

1. 순회를 돌면서 결과를 담는 result를 만든다

2. 중위 순회 함수를 재귀적으로 호출하면서 result에 순서에 맞게 결과값을 담는다

3. 재귀함수가 모두 호출된 후 결과를 반환한다

+ Recent posts