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
distanceTarget we are trying to find a chain of nodes.target met.preOrder, until we find target.preOrder traversal there.postOrder Operations and signal parent accordingly.false from both child via preOrder Signalling, we will pop out the pushed element.parents, grandparents of target, till the root.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);
}
target, parentOfTarget, ..., parent].target we will do any traversal but will stop as we found the nullptr (blockNode).parentOfTarget we will do any traversal but will stop as we found the target (blockNode).root we will do any traversal but will stop as we found the n - 2 th element (blockNode).distance which is passed as parameter.kth distance from the target.
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);
}