863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node.  The answer can be returned in any order.

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2

Output: [7,4,1]

Explanation: 
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.



Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

 

Note:

  1. The given tree is non-empty.
  2. Each node in the tree has unique values 0 <= node.val <= 500.
  3. The target node is a node in the tree.
  4. 0 <= K <= 1000.

Rust Solution

struct Solution;
use rustgym_util::*;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;

impl Solution {
    fn distance_k(root: TreeLink, p: TreeLink, k: i32) -> Vec<i32> {
        let k = k as usize;
        let mut adj: HashMap<i32, Vec<i32>> = HashMap::new();
        Self::dfs(root, &mut adj);
        let mut res = vec![];
        let mut queue: VecDeque<(i32, usize)> = VecDeque::new();
        let start = p.unwrap().borrow().val;
        let mut visited: HashSet<i32> = HashSet::new();
        visited.insert(start);
        queue.push_back((start, 0));
        while let Some((u, d)) = queue.pop_front() {
            if d == k {
                res.push(u);
            } else {
                for &mut v in adj.entry(u).or_default() {
                    if visited.insert(v) {
                        queue.push_back((v, d + 1));
                    }
                }
            }
        }
        res
    }

    fn dfs(root: TreeLink, adj: &mut HashMap<i32, Vec<i32>>) {
        if let Some(node) = root {
            let mut node = node.borrow_mut();
            let u = node.val;
            let left = node.left.take();
            let right = node.right.take();
            if left.is_some() {
                let v = left.as_ref().unwrap().borrow().val;
                adj.entry(u).or_default().push(v);
                adj.entry(v).or_default().push(u);
                Self::dfs(left, adj);
            }
            if right.is_some() {
                let v = right.as_ref().unwrap().borrow().val;
                adj.entry(u).or_default().push(v);
                adj.entry(v).or_default().push(u);
                Self::dfs(right, adj);
            }
        }
    }
}

#[test]
fn test() {
    let root = tree!(
        3,
        tree!(5, tree!(6), tree!(2, tree!(7), tree!(4))),
        tree!(1, tree!(0), tree!(8))
    );
    let p = tree!(5);
    let k = 2;
    let mut res = vec![7, 4, 1];
    let mut ans = Solution::distance_k(root, p, k);
    res.sort_unstable();
    ans.sort_unstable();
    assert_eq!(ans, res);
}

Having problems with this solution? Click here to submit an issue on github.