Print all nodes which are at K distance from root of Binary Tree

Java Implementation of printing all nodes which are at k- distance from root of a binary tree.

class Solution
{
    static class TreeNode{
        int data;
        TreeNode left,right;
        TreeNode(int data)
        {
            this.data=data;
        }
    }
    static void kDistanceNodes(TreeNode root, int k)
     {
          if(root==null)
          return;
          kDistanceNodes(root.left,k-1);
          kDistanceNodes(root.right,k-1);
          if(k==0)
          System.out.print(root.data+" ");
     }
     public static void main(String[] args)
    {
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.left=new TreeNode(4);
        root.left.right=new TreeNode(7);
        
        kDistanceNodes(root,2);
        
    }
    }

Output: 4 7

Time Complexit- O(n)

Space Complexity- O(n)

Leave a comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest