코딩 테스트 및 알고리즘/leetcode for google
leetcode easy : binary tree inorder traversal (iterative solution)
띠리링구
2022. 9. 9. 01:37
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
daily challenge에 이게 떠서 봤는데 예전에 recursive solution으로 쉽게 풀었던 문제.
이번에도 쉽게 통과했다.
근데 iterative solution으로 해결하려니까 머리가 딱 정지돼버렸다.
결국 정답을 봤는데 내가 문제를 너무 만만하게 봤던거같다.
def inorderTraversal(self, root):
res, stack = [], []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return res
node = stack.pop()
res.append(node.val)
root = node.right
스택을 왼쪽트리로 계쏙 들어가면서 쭉 쌓고
왼쪽트리가 없을때 결과리스트에 현재값을 push
그리고 오른쪽 트리에 대해 같은 작업 수행
은근히 까다롭다. iterative solution으로 풀려면 난이도가 medium~hard는 될거같은데?