题解 | #距离是K的二叉树节点#

距离是K的二叉树节点

https://www.nowcoder.com/practice/e280b9b5aabd42c9b36831e522485622

#include <unordered_map>
#include <vector>
class Solution {
private:
    int k_{};
    int target_{};
    vector<int> res_;
    unordered_map<int, TreeNode*> parents_;
public:
    void findParents(TreeNode* root) {
        if (root->left) {
            parents_[root->left->val] = root;
            findParents(root->left);
        }
        if (root->right) {
            parents_[root->right->val] = root;
            findParents(root->right);
        }
    }
    TreeNode* findNode(TreeNode* root) {
        if (!root) return nullptr;
        if (root->val == target_) return root;
        auto l = findNode(root->left);
        if (l) return l;
        auto r = findNode(root->right);
        return r;
    }
    void func(TreeNode* root, TreeNode* parent, int depth) {
        if (!root) return;
        if (depth == k_) {
            res_.push_back(root->val);
            return;
        }
        if (root->left != parent) func(root->left, root, depth + 1);
        if (root->right != parent) func(root->right, root, depth + 1);
        if (parents_[root->val] != parent) func(parents_[root->val], root, depth + 1);
    }
    vector<int> distanceKnodes(TreeNode* root, int target, int k) {
        k_ = k;
        target_ = target;
        findParents(root);
        auto tarNode = findNode(root);
        func(tarNode, nullptr, 0);
        return res_;
    }
};

全部评论

相关推荐

牛客618272644号:佬携程工作怎么样,强度大吗
点赞 评论 收藏
分享
Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务