반응형
    
    
    
  
														Notice
														
												
											
												
												
													Recent Posts
													
											
												
												
													Recent Comments
													
											
												
												- Today
- Total
작심삼일
[LeetCode] 94 | Binary Tree Inorder Traversal | Python 본문
728x90
    
    
  반응형
    
    
    
  문제 링크: https://leetcode.com/problems/binary-tree-inorder-traversal/
문제
Given the root of a binary tree, return the inorder traversal of its nodes' values.
조건
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
내 풀이
Tree 구조를 탐색할 때는 dfs로 recursive하게 하면 된다.
Inorder라는 것은 node와 node.left, node.right가 있을 때 node.left $\rightarrow$ node $\rightarrow$ node.right 순서로 진행하는 것이다.
그래서 recursive하게 탐색을 inorder(root.left) $\rightarrow$ ans.append(root.val) $\rightarrow$ inorder(root.right) 순서대로 하면 된다.
코드
# 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]:
        ans = []
        
        def inorder(root):
            nonlocal ans
            
            if not root:
                return
            
            inorder(root.left)
            ans.append(root.val)
            inorder(root.right)
            
        inorder(root)
        
        return ans728x90
    
    
  반응형
    
    
    
  '스터디 > 코테' 카테고리의 다른 글
| [LeetCode] 2007 | Find Original Array From Doubled Array | Python (0) | 2022.09.15 | 
|---|---|
| [LeetCode] 1457 | Pseudo-Palindromic Paths in an Binary Tree | Python (0) | 2022.09.14 | 
| [LeetCode] 606 | Construct String form Binary Tree | Python (0) | 2022.09.07 | 
| [LeetCode] 814 | Binary Tree Pruning | Python (0) | 2022.09.06 | 
| [LeetCode] 429 | N-ary Tree Level Order Traversal | Python (0) | 2022.09.05 | 
			  Comments