-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathditance-k.cpp
65 lines (65 loc) · 1.08 KB
/
ditance-k.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void child(TreeNode* root,vector<int>& ret,int k)
{
if(root)
{
if(!k)
ret.push_back(root->val);
else
{
child(root->left,ret,k-1);
child(root->right,ret,k-1);
}
}
}
map<TreeNode*,TreeNode*> p;
void parent(TreeNode* root,TreeNode* temp)
{
if(root)
{
p[root]=temp;
parent(root->left,root);
parent(root->right,root);
}
}
void ancestor(TreeNode* root,vector<int>& ret,int k)
{
if(root)
{
if(!k)
ret.push_back(root->val);
TreeNode* temp=p[root];
if(temp)
{
if(temp->left==root)
child(temp->right,ret,k-2);
else
child(temp->left,ret,k-2);
ancestor(temp,ret,k-1);
}
}
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int K)
{
vector<int> ret;
if(!K)
{
child(target,ret,0);
return ret;
}
child(target,ret,K);
parent(root,NULL);
ancestor(target,ret,K);
return ret;
}
};