1653. Number of Good Leaf Nodes Pairs
Medium
You are given the root
of a binary tree and an integer distance
. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance
.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2:
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].
Constraints:
- The number of nodes in the
tree
is in the range[1, 210].
1 <= Node.val <= 100
1 <= distance <= 10
<내코드 호소>
# 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 countPairs(self, root: TreeNode, distance: int) -> int:
# def inorder(root, leaf_list):
# if root:
# inorder(root.left, leaf_list)
# if root.left is None and root.right is None:
# leaf_list.append(root)
# inorder(root.right, leaf_list)
# return leaf_list
# def dfs(root, leaf_list):
# # visited = set()
# distances = -1
# stack = leaf_list
# while stack:
# leaf = stack.pop()
# leaf_list = []
# leaf_list = inorder(root, leaf_list)
# dfs(root, leaf_list)
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int:
def dfs(node):
if not node:
return []
if not node.left and not node.right : # falsy 처럼 조회
return [1]
left_distances = dfs(node.left)
right_distances = dfs(node.right)
for l in left_distances:
for r in right_distances:
if l + r <= distance:
self.result += 1
current_distances = [d + 1 for d in left_distances + right_distances if d + 1 <= distance]
print(current_distances)
return current_distances
self.result = 0
dfs(root)
return self.result
'문제풀이 > 일일연습문제' 카테고리의 다른 글
[DFS/BFS]99클럽 코테 스터디 33일차 TIL + 백준/Silver/2583. 영역 구하기 (0) | 2024.08.25 |
---|---|
[DFS/BFS]99클럽 코테 스터디 32일차 TIL + 백준/Silver/양 한마리... 양 두마리... (0) | 2024.08.25 |
[DFS/BFS]99클럽 코테 스터디 30일차 TIL + 백준/Silver/6080. Bad Grass (0) | 2024.08.22 |
[DFS/BFS]99클럽 코테 스터디 29일차 TIL + 백준/Silver/6188. Clear Cold Water (0) | 2024.08.21 |
[Binary Search]99클럽 코테 스터디 28일차 TIL + 0441-arranging-coins (0) | 2024.08.21 |