栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Leetcode】863. 二叉树中所有距离为 K 的结点

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Leetcode】863. 二叉树中所有距离为 K 的结点

题目描述

题解

用map记录每个结点的父结点,然后让dfs从target结点开始(假设target就是根结点),然后递归时纪录深度,只要深度等于k,就是和target的距离等于k,就可以存入list。

执行用时:14 ms, 在所有 Java 提交中击败了74.54%的用户

内存消耗:38.1 MB, 在所有 Java 提交中击败了98.78%的用户

class Solution{
    List res = new ArrayList<>();
    Map map = new HashMap<>();  // 
    Set set = new HashSet<>();
    int k;
    
    public List distanceK (TreeNode root, TreeNode target, int k){
        this.k = k;
        findParent(root, null);
        dfs(target, target, 0);
        return res;
    }

    public void findParent(TreeNode root, TreeNode parent) {
        if (root == null)
            return;
        map.put(root, parent);
        findParent(root.left, root);
        findParent(root.right, root);
    }
    
    public void dfs(TreeNode root, TreeNode target, int depth) {
        if (root == null || set.contains(root)) {
            return;
        }
        
        set.add(root);
        if (depth == k) {
            res.add(root.val);
            return;
        }
        // System.out.println(root.val + " " + depth);
        dfs(root.left, target, depth + 1);
        dfs(root.right, target, depth + 1);
        dfs(map.get(root), target, depth + 1);
    }
}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/287801.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号