Zero to Hero
article thumbnail
Published 2021. 4. 5. 14:09
94. Binary Tree Inorder Traversal Algorithm
 

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

1. DFS를 이용한 Inorder 구현

from typing import *


class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        answer = []

        def move(cur):
            if cur.left:
                move(cur.left)
            answer.append(cur.val)
            if cur.right:
                move(cur.right)

        move(root)
        return answer

 

2. Stack을 이용한 Inorder 구현

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        answer = []
        stack = []
        cur = root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            answer.append(cur.val)
            cur = cur.right
        return answer

 

'Algorithm' 카테고리의 다른 글

238. Product of Array Except Self  (0) 2021.04.06
46. Permutations  (0) 2021.04.05
22. Generate Parentheses  (0) 2021.04.05
2105. [모의 SW 역량테스트] 디저트 카페  (0) 2021.04.04
15. 3Sum  (0) 2021.04.02
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!