LeetCode 863. 二叉树中所有距离为 K 的结点

难度:中等。
标签:二叉树,深度优先搜索,广度优先搜索。

先找出根节点到target的路径上所有的点,将找与target的距离为k的点转换为找与路径上的点距离为find_dis的点。
注意不要重复判断。

正确解法:

/**
 * 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 {


    bool getPath(TreeNode* cur, TreeNode* target, vector<TreeNode*>& path){
        if(cur == nullptr)return false;
        if(cur == target)return true;
        if(cur->left != nullptr){
            path.emplace_back(cur->left);
            if(getPath(cur->left, target, path))return true;
            path.pop_back();
        }
        if(cur->right != nullptr){
            path.emplace_back(cur->right);
            if(getPath(cur->right, target, path))return true;
            path.pop_back();
        }
        return false;
    }

    void findNode(TreeNode* cur, int dis, vector<int>& found, TreeNode* node){
        if(cur == nullptr || cur == node)return;
        if(dis == 0){
            found.emplace_back(cur->val);
            return;
        }
        findNode(cur->left, dis - 1, found, node);
        findNode(cur->right, dis - 1, found, node);
    }

    int max(int a, int b){
        return a > b ? a : b; 
    }

    int min(int a, int b){
        return a < b ? a : b;
    }

public:
    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
        unordered_map<TreeNode*, int> maps;
        vector<TreeNode*> path;
        path.emplace_back(root);
        getPath(root, target, path);
        
        vector<int> ans;
        int begin = max(path.size() - k - 1,  0);
        for(int i = begin; i < path.size(); ++i){
            int find_dis = k - (path.size() - i - 1);
            if(find_dis == 0)ans.emplace_back(path[i]->val);
            else if(find_dis > 0){
                if(i + 1 !=  path.size())findNode(path[i], find_dis, ans, path[i + 1]);
                else findNode(path[i], find_dis, ans, nullptr);
            }
        }
        return ans;
    }
};

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值