forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
91 lines (72 loc) · 2.25 KB
/
main.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/// Source : https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/description/
/// Author : liuyubobobo
/// Time : 2018-07-01
#include <iostream>
#include <vector>
#include <cassert>
#include <queue>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Construct a Graph and Using BFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
if(K == 0)
return {target->val};
vector<vector<int>> g;
vector<int> value;
int targetIndex = -1;
constructG(g, value, root, -1, target, targetIndex);
assert(targetIndex >= 0);
int n = value.size();
assert(n == g.size());
vector<int> res;
vector<bool> visited(n, false);
queue<pair<int, int>> q;
q.push(make_pair(targetIndex, 0));
visited[targetIndex] = true;
while(!q.empty()){
int curIndex = q.front().first;
int curDis = q.front().second;
q.pop();
if(curDis == K)
res.push_back(value[curIndex]);
for(int nextIndex: g[curIndex])
if(!visited[nextIndex]){
q.push(make_pair(nextIndex, curDis + 1));
visited[nextIndex] = true;
}
}
return res;
}
private:
void constructG(vector<vector<int>>& g, vector<int>& value,
TreeNode* root, int parent, TreeNode* target, int& targetIndex){
value.push_back(root->val);
g.push_back(vector<int>());
int index = value.size() - 1;
if(parent != -1)
g[index].push_back(parent);
if(root->left != NULL){
g[index].push_back(value.size());
constructG(g, value, root->left, index, target, targetIndex);
}
if(root->right != NULL){
g[index].push_back(value.size());
constructG(g, value, root->right, index, target, targetIndex);
}
if(target == root)
targetIndex = index;
}
};
int main() {
return 0;
}