본문 바로가기
일상용/연습장

[리트코드] 3-3

by alpakaka 2025. 4. 22.

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/?envType=study-plan-v2&envId=top-interview-150

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def flatten(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: None Do not return anything, modify root in-place instead.
        """
        current = root

        while current:
            if current.left:
                predecessor = current.left
                while predecessor.right:
                    predecessor = predecessor.right
                predecessor.right = current.right
                current.right = current.left
                current.left = None
            current = current.right

 

 

 

https://leetcode.com/problems/path-sum/?envType=study-plan-v2&envId=top-interview-150

 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: Optional[TreeNode]
        :type targetSum: int
        :rtype: bool
        """
        if not root:
            return False

        ans = True

        targetSum -= root.val
        if targetSum == 0 and not root.left and not root.right:
            return True
        return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)

'일상용 > 연습장' 카테고리의 다른 글

[리트코드] 3-5회차  (0) 2025.05.11
[리트코드]3-4회차  (0) 2025.04.23
[leetcode] 3-2회차  (0) 2025.04.17
[leetcode] 3-1 회차  (0) 2025.04.15
[리트코드]2-2일차  (0) 2025.03.25