K DISTANCE

Given a balanced binary tree of integars and an integar B, count the number of pair of B distant nodes (a,b) where:

  1. a is ancestor of b
  2. value of node a - value of node b <= B

Constraints

1 <= Number of nodes in binary tree <= 100000
0 <= node values <= 10^5
1 <= B <= 10^5 

For Example

Input 1:
            1
          /   \
         2    3
        / \  / \
       4   5 6  7
      /
     8 
     B = 1
Output 1:
    1
Explaination 1:
    Possible pairs are :- {(1, 2)}

Input 2:
            1
           /  \
          2    3
           \
            4
             \
              5
    B = 2
Output 2:
    4
Explaination 2:
Possible pairs are :- {(1, 2), (1, 3), (2, 4), (4, 5)}
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving K DISTANCE on Interview Code Editor
Sign Up
to access hints and editorial solutions for K DISTANCE

Discussion


Loading...
Click here to start solving coding interview questions