具体思想:
可以记录父节点信息,变成从target向三个方向遍历,变成一个有向图;
第一次见到树转图的问题;
具体代码:
/**
* 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 getfather(TreeNode* root){
if(!root)
return;
if(root->left){
father[root->left]=root;
getfather(root->left);
}
if(root->right){
father[root->right]=root;
getfather(root->right);
}
}
void get_result(TreeNode* target,TreeNode* pre,int k){
if(k==0){
ret.push_back(target->val);
return;
}
if(target->left&&pre!=target->left)
get_result(target->left,target,k-1);
if(target->right&&pre!=target->right)
get_result(target->right,target,k-1);
if(father.find(target)!=father.end()&&father[target]!=pre)
get_result(father[target],target,k-1);
}
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
getfather(root);
get_result(target,nullptr,k);
return ret;
}
private:
map<TreeNode*,TreeNode*>father;
vector<int>ret;
};