소프트웨어에 대한 모든 것

LeetCode 풀기 - 965. Univalued Binary Tree 본문

알고리즘/LeetCode

LeetCode 풀기 - 965. Univalued Binary Tree

앤테바 2022. 1. 15. 20:47
반응형

965. Univalued Binary Tree

https://leetcode.com/problems/univalued-binary-tree/

 

Univalued Binary Tree - 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) Recursive

# 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 isUnivalTree(self, root: Optional[TreeNode]) -> bool:
        def recur(node, val):
            if node is None:
                return True
            
            if node.val != val:
                return False
            return recur(node.left, node.val) and recur(node.right, node.val)
        
        return recur(root, root.val)

 

반응형
Comments