Leaf Pairs Less Than Target Distance Away - Google Top Interview Questions
Problem Statement :
You are given a binary tree root and an integer target. Return the number of pairs of leaves such that the shortest distance between them is less than or equal to target. Constraints 0 ≤ n, target ≤ 1,000 where n is the number of nodes in root Example 1 Input root = [1, [2, [4, null, null], [5, null, null]], [3, null, null]] target = 2 Output 1 Explanation The pair (4, 5) meet the distance criteria since the distance between them is 2. Example 2 Input root = [1, [2, [4, null, null], [5, null, null]], [3, null, null]] target = 4 Output 3 Explanation Now pairs (4, 5), (3, 4) and (3, 5) meet the distance criteria.
Solution :
Solution in C++ :
vector<int> tra(Tree* root, int k, int& ans) {
if (!root) return {};
if (root->left == root->right) {
return {0, 1};
}
vector<int> left = tra(root->left, k, ans);
vector<int> right = tra(root->right, k, ans);
for (int i = 1; i < left.size(); i++) {
for (int j = 1; j < right.size(); j++) {
if (i + j <= k) {
ans += left[i] * right[j];
}
}
}
int final_len = max((int)left.size(), (int)right.size()) + 1;
vector<int> ret(final_len + 1, 0);
for (int i = 2; i < final_len; i++) {
if (left.size() >= i) ret[i] += left[i - 1];
if (right.size() >= i) ret[i] += right[i - 1];
}
return ret;
}
int solve(Tree* root, int target) {
int ans = 0;
tra(root, target, ans);
return ans;
}
Solution in Java :
import java.util.*;
/**
* public class Tree {
* int val;
* Tree left;
* Tree right;
* }
*/
class Solution {
HashMap<Tree, ArrayList<Tree>> graph;
ArrayList<Tree> leaves;
public boolean is_leaf(Tree root) {
return root.left == null && root.right == null;
}
public int solve(Tree root, int target) {
graph = new HashMap();
leaves = new ArrayList();
fill(root);
HashSet<Pair<Tree, Tree>> hs = new HashSet();
for (Tree leaf : leaves) {
int dist = 0;
LinkedList<Tree> q = new LinkedList();
HashSet<Tree> visited = new HashSet();
visited.add(leaf);
q.add(leaf);
while (q.size() > 0 && dist < target) {
int size = q.size();
for (int i = 0; i < size; i++) {
Tree cur = q.removeFirst();
visited.add(cur);
for (Tree neighbor : graph.get(cur)) {
if (visited.contains(neighbor))
continue;
if (is_leaf(neighbor))
hs.add(new Pair(neighbor, leaf));
q.addLast(neighbor);
visited.add(neighbor);
}
}
dist++;
}
}
return hs.size() / 2;
}
public void fill(Tree root) {
if (root == null)
return;
if (root.left == null && root.right == null) {
leaves.add(root);
}
graph.putIfAbsent(root, new ArrayList());
if (root.left != null) {
graph.get(root).add(root.left);
graph.putIfAbsent(root.left, new ArrayList());
graph.get(root.left).add(root);
}
if (root.right != null) {
graph.get(root).add(root.right);
graph.putIfAbsent(root.right, new ArrayList());
graph.get(root.right).add(root);
}
fill(root.left);
fill(root.right);
}
}
Solution in Python :
# class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root, target):
res = 0
def dfs(root):
nonlocal res
if not root:
return []
if root and not root.left and not root.right:
return [1]
left, right = dfs(root.left), dfs(root.right)
right.sort()
for x in left:
res += bisect.bisect(right, target - x)
return [x + 1 for x in left] + [x + 1 for x in right]
dfs(root)
return res
View More Similar Problems
Print the Elements of a Linked List
This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode
View Solution →Insert a Node at the Tail of a Linked List
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink
View Solution →Insert a Node at the head of a Linked List
Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below
View Solution →Insert a node at a specific position in a linked list
Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e
View Solution →Delete a Node
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo
View Solution →Print in Reverse
Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing
View Solution →