L30. Print all the Nodes at a distance of K in Binary Tree | C++ | Java

Поделиться
HTML-код
  • Опубликовано: 26 янв 2025

Комментарии • 284

  • @takeUforward
    @takeUforward  3 года назад +93

    Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79

    • @willturner3440
      @willturner3440 3 года назад +1

      Done brother this thing is obvious 😁

    • @ayushjain386
      @ayushjain386 3 года назад +1

      On 50 line ,i think wha pe parent_track[current]. second aana chaiye because we marked the parents like 5->3 5 ka parent 3 hai

    • @PrinceKumar-el7ob
      @PrinceKumar-el7ob 3 года назад +1

      @@ayushjain386 no it's correct 5->3 mtlb 5 ka parent 3 hai to parent_track[current] =3 hi aayega if current=5

    • @JoshMartin47
      @JoshMartin47 3 года назад

      unordered_map in c++ does take O(1) time for look up. so the time complexity in worst case will come out to O(n)

    • @soumyadeepdas1536
      @soumyadeepdas1536 2 года назад

      Bhaiya for the mark parent function there is probably no need to carry the target node seperately ig?? coz we are just marking the parent nodes for the correspnding child nodes??

  • @symbol767
    @symbol767 2 года назад +232

    To perhaps make it more clear for those still a bit confused
    He basically turned a Binary Tree into an Undirected Graph, this method is incredible and extremely useful.

    • @vivekmishra641
      @vivekmishra641 Год назад +12

      100 bat ki 1 bat

    • @someshpatel7660
      @someshpatel7660 6 месяцев назад

      Why cant we use DFS and create a mod distance variable which set to 0 at node and going away increment by 1 and on return decrement by 1. When it again comes to node, on return of that node it will -1. Here we can use absolute distance.
      Thougths?

    • @aakashpatel1250
      @aakashpatel1250 5 месяцев назад +1

      ​@@someshpatel7660this won't work if the target is on the right subtree and the k distant node is on left subtree of the root. Correct me if I misunderstood

    • @AdarshSingh-mo1kc
      @AdarshSingh-mo1kc Месяц назад

      deno....

    • @jaijaijaijai123
      @jaijaijaijai123 11 дней назад

      ​@@someshpatel7660 i used dfs to do and did it. Didn't understand what you are saying but what i did was finding descendants at k distance, then compute path from root to node marking ancestors. Now we know distance of each ancestor from node. We then move in direction away from node from these whatever steps required to get k

  • @shashankojha3452
    @shashankojha3452 3 года назад +60

    Thanks!

  • @asishcodes
    @asishcodes 2 года назад +255

    What i learned: When you have to traverse back use a map to store the parent node

    • @phatcat7924
      @phatcat7924 2 года назад +34

      these are the comments i look for they straight away go into my revision notes.

    • @prakhargupta5410
      @prakhargupta5410 2 года назад +2

      @@phatcat7924 could you please share your notes with us🥺

    • @tushar8579
      @tushar8579 Год назад +9

      @@phatcat7924 Bro he is basically making a graph and doing bfs to reach all nodes at kth level.

    • @pulkitjain5159
      @pulkitjain5159 Год назад

      yups

  • @shubhamuppal-1599
    @shubhamuppal-1599 Год назад +14

    after doing every question of this series i get to know that main motive is not to prepare for questions in interview/coding round but to identify pattern. Must say striver your content is top notch.

  • @uRamPlus
    @uRamPlus 3 года назад +208

    Self Notes:
    🍋 Mark each node to its parent to traverse upwards
    🍋 We will do a BFS traversal starting from the target node
    🍋 As long as we have not seen our node previously, Traverse up, left, right until reached Kth distance
    🍋 when reached Kth distance, break out of BFS loop and remaining node's values in our queue is our result

  • @anujjain9273
    @anujjain9273 3 года назад +32

    with this logic , i code code k distance node downwards and upwards, really impressed with the logic , dry run took time , i did it two times though , Thanks for making such content

  • @himanshugupta7010
    @himanshugupta7010 2 года назад +28

    We can implement it using recursion as well. As on every node , there will be 3 recursion .. i.e for left , for right and for parent .. code is given below ::
    void makeParent(TreeNode* root,unordered_map &parent){
    queue q;
    q.push(root);
    while(!q.empty()){
    int n= q.size();
    for(int i=0;ileft) {
    parent[node->left]=node;
    q.push(node->left);
    }
    if(node->right){
    parent[node->right]=node;
    q.push(node->right);
    }
    }
    }
    }
    class Solution {
    public:
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    unordered_map parent;
    makeParent(root,parent);
    unordered_map visited;
    vector ans;
    solve(target,parent,visited,k,ans);
    return ans;
    }
    void solve(TreeNode* target,unordered_map &parent,unordered_map &visited,int k,vector &ans){
    if(k==0){
    ans.push_back(target->val);
    }
    visited[target]=true;
    if(target->left && !visited[target->left]){
    solve(target->left,parent,visited,k-1,ans);
    }
    if(target->right && !visited[target->right]){
    solve(target->right,parent,visited,k-1,ans);
    }
    if(parent[target]!=NULL && !visited[parent[target]]){
    solve(parent[target],parent,visited,k-1,ans);
    }
    }

  • @supratimbhattacharjee5324
    @supratimbhattacharjee5324 3 года назад +123

    So basically we are traversing a tree as a graph and doing BFS from the given node

  • @_sf_editz1870
    @_sf_editz1870 Год назад +2

    here is the java code with target as integer and also target as a node thank you striver bhayya for making the concept clearer public class Solution {
    public static List distanceK(TreeNode root, int target, int k) {
    Map parent = new HashMap();
    markParents(root, null, parent);
    Queue queue = new LinkedList();
    Set visited = new HashSet();
    TreeNode tgt = findNode(target , root);
    queue.offer(tgt);
    visited.add(tgt);
    int level = 0;
    while (!queue.isEmpty()) {
    if (level == k) break;
    int size = queue.size();
    level++;
    for (int i = 0; i < size; i++) {
    TreeNode current = queue.poll();
    if (current.left != null && !visited.contains(current.left)) {
    queue.offer(current.left);
    visited.add(current.left);
    }
    if (current.right != null && !visited.contains(current.right)) {
    queue.offer(current.right);
    visited.add(current.right);
    }
    TreeNode parentNode = parent.get(current);
    if (parentNode != null && !visited.contains(parentNode)) {
    queue.offer(parentNode);
    visited.add(parentNode);
    }
    }
    }
    List result = new ArrayList();
    while (!queue.isEmpty()) {
    result.add(queue.poll().val);
    }
    Collections.sort(result);
    return result;
    }
    public static void markParents(TreeNode root, TreeNode par, Map parent) {
    if (root == null) return;
    parent.put(root, par);
    markParents(root.left, root, parent);
    markParents(root.right, root, parent);
    }
    static TreeNode findNode(int val , TreeNode root){
    if(root==null) return null;
    if(root.val == val) return root;
    TreeNode left = findNode(val , root.left);
    TreeNode right = findNode(val , root.right);
    if(left==null) return right;
    if(right == null) return left;
    return null;
    }
    }

  • @pulkitjain5159
    @pulkitjain5159 Год назад +9

    crux : converted tree into an undirected graph and applied a dfs / bfs .

  • @pratyushnarain5220
    @pratyushnarain5220 3 года назад +17

    you can also do it in O(H) space by stroring root to target node path and then calling the k-down function on them.

    • @nikhilmeena8585
      @nikhilmeena8585 2 года назад

      even we can do it without storing the root to that node path , by just checking whether if a nodes leftchild contains target , then we will search for possible answers in the right subtree of current node , and if found in rightNode then w will check possible answers in left subtree , if the node is itself target than we can just see all its childrens at distance k.

    • @aastikmehta9093
      @aastikmehta9093 Месяц назад

      ​@@nikhilmeena8585nope it fail in some of the test cases

  • @gandhijainamgunvantkumar6783
    @gandhijainamgunvantkumar6783 2 года назад +8

    What an amazing explanation. I was able to do the whole code by myself just after you did a dry run and told the logic. Thank you so much bhaiya for making trees easy for us. :)

  • @Anonymous-uj3jx
    @Anonymous-uj3jx 2 года назад +10

    Why everything becomes soo easy when striver teaches it ? Mann you are magical 💖

  • @ishangujarathi10
    @ishangujarathi10 Год назад +2

    Superb Intuition and explanation, this problem falls in the range of Hard Problem, but your technique and approach makes it super easy to understand and also code!!

  • @rajatrajgautam3224
    @rajatrajgautam3224 8 месяцев назад +1

    I basically learned if we want to go backward in a tree we need to use a map to store the parent node.........Incredible !

  • @deepakjain4481
    @deepakjain4481 Год назад +1

    i think for this method we should have used 3 pointers in a binary tree left right and parent while constructing tree and then simply traverse the tree and finding the target of the tree and then using a map i which two variable are there int for distance and node for distinct element

  • @armaanhadiq3741
    @armaanhadiq3741 Год назад +5

    Basically, here we are making the undirected graph from given tree and using BFS(level order traversal of graph) to find different vertices at distance k

    • @pulkitjain5159
      @pulkitjain5159 Год назад

      yes

    • @beamncrash9971
      @beamncrash9971 Год назад +1

      yeah more like creating a adjaceny list and then doing BFS from target node

  • @vaibhavgupta973
    @vaibhavgupta973 3 года назад +1

    starting mae toh ache samaj nhi aa rha tha .
    but jaise hi code walk through kra ... sab samaj aa gaya ache se.
    Thanks!!

  • @willturner3440
    @willturner3440 3 года назад +6

    For me this is the most awaited video..
    Love you striver 😍

  • @iWontFakeIt
    @iWontFakeIt 2 года назад +2

    here, the problem in leetcode has constraints given that 0

  • @solankiketul5640
    @solankiketul5640 8 месяцев назад +1

    I have one more solution with time complexity O(2n) and space complexity O(n).
    1.) Take a map which stores the pair (Node value, direction from root, left or right), eg, (4, left)
    2.) in the process, store the level of the target and the direction, level=1, direction= left
    3.) if the target is on left, take all the values from level+k with direction left. In our eg, from map[3], we will get 7 and 4
    4.) now for ancestor, take map[k-level], so we will have map[1] and as the target value is on left, we will take the nodes with direction right from map[1]. In our example it is 1.

  • @teja1384
    @teja1384 2 года назад +1

    if we have to traverse a tree upward then we have to make parent map which store the parent of every node , Nice explanation.

  • @tusharnain6652
    @tusharnain6652 2 года назад +6

    There is no need of passing target to makr parent function.

  • @haripriya8034
    @haripriya8034 2 месяца назад

    we also do the problem like keeping a hashtable for distance and find all the distances from the root node for the left side... and for the right side as seperate.. and then we can find the nodes with that distance.

  • @SibiRanganathL
    @SibiRanganathL 3 месяца назад

    I just coded the solution with the explanation . THANK YOU STRIVER BHAI

  • @riteshkhadse4517
    @riteshkhadse4517 3 года назад +4

    to mark visited nodes we can use set instead of map.

  • @gouravkumar7459
    @gouravkumar7459 3 года назад

    The easiest explanation for this problem so far on youtube.

  • @5076_GidijalaDineshSurya
    @5076_GidijalaDineshSurya 4 месяца назад

    Guys, this question was asked in Amazon interview. The twist is that we should not use a map to store the parents. Try solving it without using the map! Loved the explanation Striver!!

  • @jaijaijaijai123
    @jaijaijaijai123 11 дней назад

    Another way is to record ancestors and then traverse away from node from these ancestors. whatever distance needed:
    void descendents(TreeNode* root, int k,vector&res)
    {
    if(root==NULL || kval);
    descendents(root->left,k-1,res);
    descendents(root->right,k-1,res);
    }
    void ancestorcompute(TreeNode* root,TreeNode*target, vector&anc,bool&flag)
    {
    if(root==NULL||flag)
    return;
    anc.push_back(root);
    if(root==target)
    {
    flag=true;
    return;
    }
    ancestorcompute(root->left,target,anc,flag);
    if(!flag)
    ancestorcompute(root->right,target,anc,flag);
    else
    return;
    if(!flag)
    anc.pop_back();
    }
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    if(root==NULL)
    return {};
    vectorres;
    //first compute in descendants
    descendents(target,k,res);
    //find ancestors of node
    vectoranc;
    bool flag=false;
    ancestorcompute(root,target,anc,flag);
    int sz=anc.size();
    for(int j=sz-2;j>=0;j--)
    {
    if(sz-1-j==k){
    res.push_back(anc[j]->val);
    break;
    }
    else if(anc[j]->left==anc[j+1])
    {
    //go in right
    descendents(anc[j]->right,k-1-(sz-1-j),res);
    }
    else
    {
    descendents(anc[j]->left,k-1-(sz-1-j),res);
    }
    }
    return res;
    }

  • @sikandarchaudharyzx9014
    @sikandarchaudharyzx9014 2 года назад +2

    Sometimes you make the easy questions very complex.

  • @rohan8758
    @rohan8758 9 месяцев назад

    Key Notes:
    - Mark each node to its parent to traverse upwards
    - We will do a BFS traversal starting from the target node
    - As long as we have not seen our node previously, Traverse up, left, right until reached Kth distance
    - When reached Kth distance, break out of BFS loop and remaining node's values in our queue is our result.

  • @sharmanihal99
    @sharmanihal99 7 месяцев назад

    Python Code to Find all Nodes a K Distance in Binary Tree:
    #Thanks for the Great Explanation
    class Solution:
    def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
    # Function to perform breadth-first search to find parent nodes
    def bfs_to_find_parents(root):
    parent_map = {} # Maps a node's value to its parent node
    if not root:
    return parent_map
    queue = deque()
    queue.append(root)
    while queue:
    node = queue.popleft()
    if node.left:
    queue.append(node.left)
    parent_map[node.left.val] = node # Store parent for left child
    if node.right:
    queue.append(node.right)
    parent_map[node.right.val] = node # Store parent for right child
    return parent_map

    # Function to find nodes at distance k from the target node
    def find_nodes_with_distance_k(target, parent_map, k):
    queue = deque()
    queue.append(target)
    visited = set()
    visited.add(target.val)
    distance = 0
    while distance != k:
    size = len(queue)
    while size:
    node = queue.popleft()
    # Check if parent exists and it hasn't been visited before
    if parent_map[node.val] and parent_map[node.val].val not in visited:
    queue.append(parent_map[node.val]) # Add parent to queue
    visited.add(parent_map[node.val].val) # Mark parent as visited
    # Add left child to queue if it exists and hasn't been visited
    if node.left and node.left.val not in visited:
    queue.append(node.left)# Add left child to queue
    visited.add(node.left.val)# Mark left child as visited
    # Add right child to queue if it exists and hasn't been visited
    if node.right and node.right.val not in visited:
    queue.append(node.right)# Add right child to queue
    visited.add(node.right.val)# Mark right child as visited
    size -= 1
    distance += 1
    return queue


    # Build parent map
    parent_map = bfs_to_find_parents(root)
    parent_map[root.val] = None # Set root's parent as None

    # Find nodes at distance k from target
    nodes_at_distance_k = find_nodes_with_distance_k(target, parent_map, k)

    # Extract values of nodes at distance k
    result = [node.val for node in nodes_at_distance_k]
    return result

  • @satyamsrivastava9034
    @satyamsrivastava9034 3 года назад +14

    I encountered this problem in one of the interview I told him the approach which you have explained then he told me not to use the map to store the parents .. and then I shattered as I don't have that approach in mind. :(

    • @mukulsaluja6109
      @mukulsaluja6109 3 года назад +1

      U can store root to target node path

    • @saikrishnalanka133
      @saikrishnalanka133 3 года назад +6

      In the first step you can find the nodes which are at k distance below given node using recursive traversal. Then back track to each ancestor and store distance of ancestor in variable ( say d). Back track until k-d!=0. and at each ancestor call recursive again to find node at distance k-d.

    • @chirayubaliyan5181
      @chirayubaliyan5181 2 года назад

      what about pair, you can use that also!Maybe!

  • @harshjhunjhunuwala
    @harshjhunjhunuwala 2 года назад +3

    Actually there's no need of "target" parameter in markParent function as it isn't used anywhere!

  • @chandrachurmukherjeejucse5816
    @chandrachurmukherjeejucse5816 Год назад +1

    I solved it myself by another approach. Please let me know If It is a good approach or not.
    1. Storing the path from root the the node in a deque using a dfs.
    2. keep a count for how many elements are popped from deque
    2. pop items from the front of deque and find the nodes at a dist (n - no of items popped).
    3. Now to make sure that the latter popped node doesnot searches in the direction of the node popped previously we use a unordered set of popped out elements and after finding nodes at a dist for a node we put the node in the unordered set.
    Code: class Solution {
    private:
    bool dfs(TreeNode* root, TreeNode* target, deque &dq) {
    if(root == NULL) return false;
    if(root == target) {
    dq.push_back(target);
    return true;
    }
    bool isFound = false;
    isFound = dfs(root -> left, target, dq);
    isFound = isFound || dfs(root -> right, target, dq);
    if(isFound) {
    dq.push_back(root);
    return true;
    }
    return false;
    }
    void getAllNodes(TreeNode* curr, unordered_set &s, int dist, vector &res) {
    if(curr == NULL) return;
    if(s.find(curr) != s.end()) return;
    if(dist == 0) {
    res.push_back(curr -> val);
    return;
    }
    getAllNodes(curr -> left, s, dist - 1, res);
    getAllNodes(curr -> right, s, dist - 1, res);
    }
    public:
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    deque dq;
    unordered_set s;
    dfs(root, target, dq);
    vector res;
    int dist = k;
    while(!dq.empty()) {
    TreeNode* curr = dq.front();
    dq.pop_front();
    getAllNodes(curr, s, dist--, res);
    s.insert(curr);
    if(dist < 0) break;
    }
    return res;
    }
    };

  • @stith_pragya
    @stith_pragya 7 месяцев назад +1

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @Yash-uk8ib
    @Yash-uk8ib 3 года назад +5

    I initiallly thought of actually converting this tree to an undirected graph and just finding K distant nodes but your observation is just best!!
    Can u tell me why u took visited array??

    • @takeUforward
      @takeUforward  3 года назад +4

      So that I dont go back to them..

    • @Yash-uk8ib
      @Yash-uk8ib 3 года назад

      @@takeUforward sir u can visit back only parent nodes right? And that can be maintained using a variable?

    • @deepaktiwari7059
      @deepaktiwari7059 2 года назад

      @@Yash-uk8ib We can also revisit the target node from parent node(for eg 3 to 5)

  • @BinduMahapatra-sq6vh
    @BinduMahapatra-sq6vh 7 месяцев назад +1

    Ek TVF and dusra TUF bas ye dono hee rocking hai abhi tou.

  • @tanishq2766
    @tanishq2766 Год назад

    I solved it differently(return all the downward nodes at a distance k from some particular node and some simple manipulations), but i think this approach is easier to come up with if someone have studied standard graph problems

  • @NeerajSharma-mz4es
    @NeerajSharma-mz4es 3 года назад +2

    I leanned a new approach thanks to u sir

  • @nihalnandannayak8869
    @nihalnandannayak8869 Год назад +1

    What is the need of passing target node as argument of the function markparen()

  • @danielredcliff235
    @danielredcliff235 Месяц назад

    simple to understand code , thank you

  • @apmotivationakashparmar722
    @apmotivationakashparmar722 3 месяца назад

    Thank you so much Striver !.

  • @ayushgautam8000
    @ayushgautam8000 5 месяцев назад

    GOD Level Explanation 🫡🫡

  • @nagavedareddy5891
    @nagavedareddy5891 2 года назад +4

    Perfect and most efficient explanation.. But small optimisation would be using hash set instead of Hashmap for visited.

  • @ritikshandilya7075
    @ritikshandilya7075 5 месяцев назад

    Thankyou so much for great explanation Striver

  • @1234abcd-qt6uz
    @1234abcd-qt6uz Год назад

    for getting nodes at distance k
    visited map and array is not required
    only previous node is enough so that it doesn't call back
    (visited not required because this is not cyclic graph)
    for getting nodes at distance k CODE
    void dfsNodesAtDistanceK(TreeNode *node, TreeNode *pre, int k, unordered_map &parentMap, vector &ans) {
    if (k==0) {
    ans.push_back(node->val);
    return;
    }
    if (node->left && node->left!=pre) {
    dfsNodesAtDistanceK(node->left, node, k-1, parentMap, ans);
    }
    if (node->right && node->right!=pre) {
    dfsNodesAtDistanceK(node->right, node, k-1, parentMap, ans);
    }
    TreeNode *parent = parentMap[node];
    if (parent!=NULL && parent!=pre) {
    dfsNodesAtDistanceK(parent, node, k-1, parentMap, ans);
    }
    return;
    }
    FULL CODE
    class Solution {
    private:
    void markParents(TreeNode *root, unordered_map &parentMap) {
    queue nodeQueue;
    nodeQueue.push(root);
    while (!nodeQueue.empty()) {
    TreeNode *node = nodeQueue.front();
    nodeQueue.pop();
    if (node->left) {
    parentMap[node->left] = node;
    nodeQueue.push(node->left);
    }
    if (node->right) {
    parentMap[node->right] = node;
    nodeQueue.push(node->right);
    }
    }
    return;
    }
    void dfsNodesAtDistanceK(TreeNode *node, TreeNode *pre, int k, unordered_map &parentMap, vector &ans) {
    if (k==0) {
    ans.push_back(node->val);
    return;
    }
    if (node->left && node->left!=pre) {
    dfsNodesAtDistanceK(node->left, node, k-1, parentMap, ans);
    }
    if (node->right && node->right!=pre) {
    dfsNodesAtDistanceK(node->right, node, k-1, parentMap, ans);
    }
    TreeNode *parent = parentMap[node];
    if (parent!=NULL && parent!=pre) {
    dfsNodesAtDistanceK(parent, node, k-1, parentMap, ans);
    }
    return;
    }
    public:
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    unordered_map parentMap;
    markParents(root, parentMap);
    vector ans;
    dfsNodesAtDistanceK(target, NULL, k, parentMap, ans);
    return ans;
    }
    };
    863. All Nodes Distance K in Binary Tree

  • @Yag116
    @Yag116 Год назад +1

    Solution :where we are given value of target Node
    void markparent(Node* root , unordered_map &keep_parent,int t,Node* &tn ){
    if(!root) return;
    queue q;
    q.push(root);
    while(!q.empty()){
    int n = q.size();
    for(int i=0;idata==t) tn=root; //only for getting target node form given key
    if(root->left){
    keep_parent[root->left]=root; // root k left ka parent root mark kr diya
    q.push(root->left);
    }
    if(root->right){
    keep_parent[root->right]=root; // root k right ka parent root mark kr diya
    q.push(root->right);
    }
    }
    }
    }


    vector KDistanceNodes(Node* root , int target , int k){
    unordered_map Keep_parent ;
    Node* targetN =NULL;
    markparent(root,Keep_parent,target,targetN); // sare parent aa gye
    unordered_map visted;
    queue q;
    q.push(targetN);
    visted[targetN] = true;
    int curr_dist=0;
    while(!q.empty()){
    int size = q.size();
    if(curr_dist++ == k) break;
    for(int i=0;ileft && !visted[curr->left]) {
    q.push(curr->left);
    visted[curr->left]=true;
    }
    if(curr->right && !visted[curr->right]) {
    q.push(curr->right);
    visted[curr->right]=true;
    }
    if(Keep_parent[curr] && !visted[Keep_parent[curr]]) {
    q.push(Keep_parent[curr]);
    visted[Keep_parent[curr]]=true;
    }
    }
    }
    vector ans;
    while(!q.empty()){
    Node* temp = q.front();
    q.pop();
    ans.push_back(temp->data);
    }
    sort(ans.begin(),ans.end());
    return ans;
    }

  • @charlesbabbage6786
    @charlesbabbage6786 9 месяцев назад

    What a mind blowing solution!!

  • @infinityzero2321
    @infinityzero2321 Год назад

    I am thinking of anotger approach which is treating this like a directed graph. So instead of marking that whuch is the nodes parent we can just make an adj list and mark them like an undirected graph. Then we can directly do the bfs

  • @vaibhav56
    @vaibhav56 Год назад

    Solution without using any extra space for storing the parent:
    class Solution {
    public:
    vector ans;
    void down(TreeNode* target,int k){
    if(!target)return;
    if(k==0){
    ans.push_back(target->val);
    return;
    }
    down(target->left,k-1);
    down(target->right,k-1);
    }
    bool up(TreeNode* root,TreeNode* target,int &k){
    if(!root)return false;
    if(root==target)return true;
    if(up(root->left,target,k)){
    k--;
    if(k==0)ans.push_back(root->val);
    down(root->right,k-1);
    return true;
    }
    if(up(root->right,target,k)){
    k--;
    if(k==0)ans.push_back(root->val);
    down(root->left,k-1);
    return true;
    }
    return false;
    }
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    down(target,k);
    up(root,target,k);
    return ans;
    }
    };

  • @paritoshdadhich2954
    @paritoshdadhich2954 Год назад

    Thank you for the best possible solution. Hats off to your efforts

  • @bmuralikrishna8054
    @bmuralikrishna8054 Месяц назад

    Following is the solution using the Backtracking. In interviews, you may be asked to write without storing the parent pointers in the MAP.
    ===> Assume the Solution::solve() returns the vector with list of nodes at a distance of K from the target node.
    void findNodeAtGivenDist(TreeNode *root, vector &ans, int distance){
    if(root == NULL)
    return;

    if(distance == 0)
    ans.push_back(root -> val);

    findNodeAtGivenDist(root -> left, ans, distance - 1);
    findNodeAtGivenDist(root -> right, ans, distance - 1);
    }
    int solve1(TreeNode *root, int target, int distance, vector &ans){
    if(root == NULL)
    return 0;

    if(root -> val == target){
    // Find the bottom nodes from the target
    findNodeAtGivenDist(root, ans, distance);
    return 1;
    }
    int left = solve1(root -> left, target, distance, ans);
    int right = solve1(root -> right, target, distance, ans);
    if(left == distance || right == distance)
    {
    // Edge case, the current node is exactly equal to the distance
    ans.push_back(root -> val);
    }
    if(left > 0){
    // Go to the right side and find the nodes with the given distance
    findNodeAtGivenDist(root -> right , ans, distance - left - 1);
    return left + 1;
    }
    if(right > 0){
    findNodeAtGivenDist(root -> left, ans, distance - right - 1);
    return right + 1;
    }
    return 0;
    }
    vector Solution::solve(TreeNode* A, int B, int C) {
    vector ans;
    solve1(A, B, C, ans);
    return ans;
    }

  • @4747surya
    @4747surya Год назад

    Basically convert tree into a undirected graph start from target and do k iteration of BFS ?

  • @theghost9362
    @theghost9362 Год назад

    ommmg , thanks , I was doing something completely different , I was trying to compute a list that represent that BT , and then compute the the parent and children K times until i get the result , but you're algo is a lot faster

  • @Vanshikataneja-r5w
    @Vanshikataneja-r5w 8 месяцев назад

    You are magic striver and you create magic

  • @harshmittal3128
    @harshmittal3128 2 года назад

    Thanks for such a great explanation striver...
    This was a very good question , learnt multiple new approaches from this one ..

  • @vedantsharma5876
    @vedantsharma5876 3 года назад +3

    Should this(or a similar) question be asked in an interview? Because it took me almost 1 hour to just code!

    • @amanbhadani8840
      @amanbhadani8840 3 года назад +3

      Yes definitely,You have to work on your speed.

  • @gubbalamalleswari5892
    @gubbalamalleswari5892 Год назад +1

    Super explanation

  • @abhineetkapil
    @abhineetkapil Год назад

    Nice and easy explaination. !

  • @aryashjain7893
    @aryashjain7893 2 года назад +1

    Ill do this again , accha problem hai revision lagega
    thenks striver

  • @rahatsshowcase8614
    @rahatsshowcase8614 3 года назад +2

    Why we take the target arguement in markparents function?

  • @cinime
    @cinime 2 года назад

    Understood! Such a fantastic explanation as always, thank you very much!!

  • @parthsalat
    @parthsalat 2 года назад +1

    Please do a smooth transition from black iPad to white Code screen...I've become blind because of the quick transition 😥

  • @vanshajtiwari1282
    @vanshajtiwari1282 7 месяцев назад

    Love you bhai love you, You are amazing, amazing explaination.

  • @ransh-sahu
    @ransh-sahu 5 месяцев назад

    the 2nd toughest quetion so far of this series

  • @prekshaswami3142
    @prekshaswami3142 Год назад

    why have we taken target as one of the argument in markParents function?

  • @051-avnee4
    @051-avnee4 Год назад

    Awesome explanation 💫💫!!!
    Understood .....

  • @rishabsharma5307
    @rishabsharma5307 3 года назад +2

    please make videos on finding time complexity of finding complex questions

    • @takeUforward
      @takeUforward  3 года назад +2

      Comes with practice, don't think on that too much :)

  • @gigglezone3432
    @gigglezone3432 Год назад

    I solved it by converting tree to graph, and take adjacency list and bfs to traverse to all nodes at a distance of k? Is it a good approach for interviews?

  • @adityaanand1912
    @adityaanand1912 2 месяца назад

    bhai kya gaaannnddddd faaaaadddd playlist hai maza aagaya

  • @DevanshuAugusty
    @DevanshuAugusty 2 года назад

    why are you passing the target node int mark parent function?

  • @palakmantry
    @palakmantry 3 года назад +2

    Thank you for the explanation, really helpful

  • @prashantpandey2848
    @prashantpandey2848 2 года назад

    we can avoid second loop using one more queue

  • @bhashkarbelwal4116
    @bhashkarbelwal4116 10 месяцев назад

    you are amazing tutor #takeuForward bro

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 2 года назад +1

    Amazing explanation😇

  • @shivampratapsingh2188
    @shivampratapsingh2188 Год назад

    I have one doubt -this above apprach will get fail when tree will not be a binary tree right??

  • @sparshsharma6068
    @sparshsharma6068 3 года назад

    Very well explained bhaiya! understood🔥

  • @jivanmainali1742
    @jivanmainali1742 5 месяцев назад

    So purpose was to convet tree into undirected graph

  • @AKASHKUMAR-li7li
    @AKASHKUMAR-li7li 7 месяцев назад

    This can be easily solved using
    1) root to node path
    2) print all nodes k level down

  • @shrutishreya7773
    @shrutishreya7773 Год назад

    why are we taking target as parameter in markparents function

  • @ayushgautam8000
    @ayushgautam8000 5 месяцев назад

    GOD level explanation 🫡🫡

  • @rijumondal6876
    @rijumondal6876 Год назад

    Do I need to go with a brute-better-optimal solution for this approach in the interview if asked??

    • @harishms5330
      @harishms5330 4 месяца назад

      Yes, that's the way u need to go

  • @KaifKhan-sb2yr
    @KaifKhan-sb2yr Год назад

    why time complexity is o(N) why not o(N)square perhaps we are using two nested loops please tell ..i am a beginner

  • @ishachauhan6477
    @ishachauhan6477 7 месяцев назад

    very well explained thankyou sir

  • @SUMITKAUSHIK1000
    @SUMITKAUSHIK1000 2 года назад +2

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) { val = x; }
    * }
    */
    class Solution {
    public List distanceK(TreeNode root, TreeNode target, int k) {
    Map map = new HashMap();
    Set visited = new HashSet();
    List list = new ArrayList();
    updateParent(null, root, map);
    traverse(k, target, map, list, visited);
    return list;
    }


    public void updateParent(TreeNode parent, TreeNode current, Map childToParent){

    if(current == null)
    return;

    childToParent.put(current, parent);

    updateParent(current, current.left, childToParent);
    updateParent(current, current.right, childToParent);

    }

    public void traverse(int distance, TreeNode node, Map childToParent,
    List list, Set visited){

    if(node == null)
    return;

    if(visited.contains(node))
    return;

    visited.add(node);

    if(distance == 0){
    list.add(node.val);
    return;
    }

    traverse(distance-1, node.left, childToParent, list, visited);
    traverse(distance-1, node.right, childToParent, list, visited);
    traverse(distance-1, childToParent.get(node), childToParent, list, visited);
    }
    }

  • @silicon9794
    @silicon9794 2 года назад

    Good explanation bro. Understood properly. Thankyou :)

  • @littleblackhat2142
    @littleblackhat2142 2 года назад +1

    How do we solve this without using parent pointers or without any extra space? Is it even possible? I was asked this question in Amazon interview and the interviewer was persistent on solving without space and ultimately it led to me bombing the interview :(

  • @g.upenderreddy
    @g.upenderreddy Год назад

    we could use Set to keep track of visited nodes.
    public List distanceK(TreeNode root, TreeNode target, int k) {
    Map parentMap = markParentNodes(root);
    Set visited = new HashSet();
    Deque queue = new LinkedList();
    visited.add(target);
    queue.offer(target);
    int currentLevel = 0 , size = 0;
    while (!queue.isEmpty()) {
    if (currentLevel == k) break;
    currentLevel++;
    size = queue.size();
    for (int i = 0; i< size; i++) {
    TreeNode node = queue.poll();
    if (node.left != null && !visited.contains(node.left)) {
    queue.offer(node.left);
    visited.add(node.left);
    }
    if (node.right != null && !visited.contains(node.right)) {
    queue.offer(node.right);
    visited.add(node.right);
    }
    TreeNode parent = parentMap.get(node);
    if (parent != null && !visited.contains(parent)) {
    queue.offer(parent);
    visited.add(parent);
    }
    }
    }
    return queue.stream().map(node -> node.val).toList();
    }
    public Map markParentNodes(TreeNode root) {
    Map parentMap = new HashMap();
    // store
    Deque queue = new LinkedList();
    queue.offer(root);
    while (!queue.isEmpty()) {
    TreeNode node = queue.poll();
    if (node.left != null) {
    parentMap.put(node.left, node);
    queue.offer(node.left);
    }
    if (node.right != null) {
    parentMap.put(node.right, node);
    queue.offer(node.right);
    }
    }
    return parentMap;
    }

  • @jothsna
    @jothsna Год назад

    Nice explanation☺

  • @NoName-hd7ok
    @NoName-hd7ok 6 месяцев назад +1

    Store parents and do normal bfs using visited array

  • @aakriti1
    @aakriti1 2 года назад

    Understood, Great explanation! 🤩

  • @ajitheshgupta3017
    @ajitheshgupta3017 2 года назад

    If it was print all from lead node. What changes has to be done?

  • @Abhishek-do8mp
    @Abhishek-do8mp 3 года назад +1

    just one word - amazing

  • @pritamsaha7129
    @pritamsaha7129 Год назад

    What happens when we get two nodes of same value?? Will unordered map work at that time??

  • @neerajgarg9096
    @neerajgarg9096 2 года назад

    class Solution {
    private:
    void mapping(TreeNode* root, map&nodetoparent){
    if(root==NULL){
    return;
    }
    nodetoparent[root]=NULL;
    queueq;
    q.push(root);
    while(!q.empty()){
    TreeNode* front=q.front();
    q.pop();
    if(front->left){
    nodetoparent[front->left]=front;
    q.push(front->left);
    }
    if(front->right){
    nodetoparent[front->right]=front;
    q.push(front->right);
    }
    }
    }
    public:
    vector distanceK(TreeNode* root, TreeNode* target, int k) {
    mapnodetoparent;
    mapping(root, nodetoparent);

    queueq;
    q.push(target);
    mapvisited;
    visited[target]=true;
    int d=0;
    while(d!=k){
    int size=q.size();
    for(int i=0; ileft && visited[front->left]==false){
    visited[front->left]=true;
    q.push(front->left);
    }
    if(front->right && visited[front->right]==false){
    visited[front->right]=true;
    q.push(front->right);
    }
    if(nodetoparent[front] && visited[nodetoparent[front]]==false){
    visited[nodetoparent[front]]=true;
    q.push(nodetoparent[front]);
    }
    }
    d++;
    }
    vectorres;
    while(!q.empty()){
    TreeNode* front = q.front();
    res.push_back(front->val);
    q.pop();
    }
    return res;
    }

  • @amisha2545
    @amisha2545 3 года назад

    🔥couldn’t have been better!

  • @AlokKumar-ld9qr
    @AlokKumar-ld9qr 2 года назад

    amazing explanation. 😃😃😃

  • @ayushidalal5488
    @ayushidalal5488 2 года назад

    Amazing explanation! Thankyou so much :)