category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

863. All Nodes Distance K in Binary Tree

Block Node concept

Distance target

public boolean distanceTarget(TreeNode root, TreeNode target) {
    if (root == null) {
        return false;
    }
    if (root.val == target.val) {
        arr.add(root);
        return true;
    }

    arr.add(root);
    boolean left = distanceTarget(root.left, target);
    boolean right = distanceTarget(root.right, target);

    if (left == false && right == false) {
        if (!arr.isEmpty())
            arr.remove(arr.size() - 1);
        return false;
    }
    return (left || right);
}

Dist


void dist(TreeNode root, TreeNode blocked, int k) {
    if (root == null) {
        return;
    }
    if (root == blocked) {
        return;
    }
    if (k == 0) {
        ans.add(root.val);
    }
    dist(root.left, blocked, k - 1);
    dist(root.right, blocked, k - 1);
}

Complete implementation ```java class Solution { ArrayList arr; ArrayList ans; public boolean distanceTarget(TreeNode root, TreeNode target) { if (root == null) { return false; } if (root.val == target.val) { arr.add(root); return true; } arr.add(root); boolean left = distanceTarget(root.left, target); boolean right = distanceTarget(root.right, target); if (left == false && right == false) { if (!arr.isEmpty()) arr.remove(arr.size() - 1); return false; } return (left || right); } void dist(TreeNode root, TreeNode blocked, int k) { if (root == null) { return; } if (root == blocked) { return; } if (k == 0) { ans.add(root.val); } dist(root.left, blocked, k - 1); dist(root.right, blocked, k - 1); } public List distanceK(TreeNode root, TreeNode target, int k) { arr = new ArrayList(); ans = new ArrayList(); distanceTarget(root, target); Collections.reverse(arr); for (var i: arr) { System.out.print(i.val + " "); } System.out.println(""); for (int i = 0; i <= Math.min(k, arr.size() - 1); i++) { dist(arr.get(i), i == 0 ? null : arr.get(i - 1), k - i); } return ans; } } ``` </details>