파비의 매일매일 공부기록

2023.10.17 Today's Challenge 본문

Problem Solving/LeetCode

2023.10.17 Today's Challenge

fabichoi 2023. 10. 17. 23:45

https://leetcode.com/problems/validate-binary-tree-nodes/

 

Validate Binary Tree Nodes - LeetCode

Can you solve this real interview question? Validate Binary Tree Nodes - You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one val

leetcode.com

트리니까 보통의 방법인 BFS/DFS 로 풀면 됨

class Solution:
    def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
        def find_root():
            children = set(leftChild) | set(rightChild)
            for i in range(n):
                if i not in children:
                    return i
            return -1
        
        root = find_root()
        if root == -1:
            return False
        
        seen = {root}
        stack = [root]
        while stack:
            node = stack.pop()
            for child in [leftChild[node], rightChild[node]]:
                if child != -1:
                    if child in seen:
                        return False
                    stack.append(child)
                    seen.add(child)
        
        return len(seen) == n
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.10.19 Today's Challenge  (0) 2023.10.19
2023.10.18 Today's Challenge  (0) 2023.10.18
2023.10.16 Today's Challenge  (0) 2023.10.16
2023.10.15 Today's Challenge  (0) 2023.10.15
2023.10.14 Today's Challenge  (0) 2023.10.14
Comments