728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.
문제는 여기서 볼 수 있습니다.
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Code:
# 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
# recursively
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right) if root else []
# iteratively
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
nodes = []
answer = []
while True:
while root:
# 각 노드 보관
nodes.append(root)
# 다음 왼쪽 자식 노드 탐색
root = root.left
# nodes가 비어있을 경우(모든 노드 탐색) 탐색 종료
if not nodes:
return answer
# 가장 최근에 탐색한 노드 꺼내어 answer 리스트에 값 추가
node = nodes.pop()
answer.append(node.val)
# 현재 시점으로, 가장 왼쪽의 노드를 탐색했으므로
# 다음으로는 오른쪽 노드 탐색(중간 노드는 바로 위에서 리스트에 추가했음)
root = node.right
return answer
차근차근 생각해보면 풀릴 수 있는 문제 같다.
하지만 쉽게 풀리진 않는다.
이 코드들을 그냥 대강이라도 외워야겠다.
728x90
'알고리즘' 카테고리의 다른 글
[Leetcode/Python] Happy Number (0) | 2022.11.29 |
---|---|
[Leetcode/Python] Jump Game (0) | 2022.11.25 |
[Leetcode/Python] Missing Number (0) | 2022.11.21 |
[Leetcode/Python] Reverse Bits (0) | 2022.11.21 |
[Leetcode/Python] Convert Sorted Array to Binary Search Tree (0) | 2022.11.17 |