-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKdistance.cpp
More file actions
46 lines (46 loc) · 1.04 KB
/
Copy pathKdistance.cpp
File metadata and controls
46 lines (46 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<iostream>
#include<vector>
#include<queue>
#include<set>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void helper(TreeNode* root,const int& min,const int& max, int &pairs){
if(!root){
return;
}
if(root->val==min || root->val==max){
++pairs;
}
else if(root->val>min || root->val<max){
++pairs;
}
helper(root->left, min, max,pairs);
helper(root->right,min, max,pairs);
}
int solve(TreeNode* A, int B){
int pairs = 0;
//do inorder traversal
std::queue<TreeNode*> q;
q.push(A);
while(!q.empty()){
TreeNode* curr = q.front();
int min = curr->val - B;
if(min<0){
min = 0;
}
int max = curr->val + B;
helper(curr->left,min, max,pairs);
helper(curr->right, min, max, pairs);
if(curr->left){
q.push(curr->left);
}
if(curr->right){
q.push(curr->right);
}
}
return pairs;
}