title: Find the Elements within the given distance within Tree
body: <p>I have a tree which as certain elements, I have a method essentially returns a list of elements that are within the distance. </p>
  
  <p>Example</p>
  
  <p><a href="https://i.stack.imgur.com/Qhnjq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qhnjq.png" alt="enter image description here"></a></p>
  
  <p>In the tree above, once I have my method, I should be able to input a data and distance. Lets say the data I input is 1 and the distance is 2. In this case, the method should output elements, [2,3,4] because I should be able to output data that is less than or equal to the given distance.</p>
  
  <p>I know how to output data that have a distance of 2 away, but I am struggling to include data that includes data that is 1 away as well. </p>
  
  <pre><code>    void printkdistanceNodeDown(Node node, int k)  
      { 
          if (node == null || k &lt; 0) 
              return; 
          if (k == 0)  
          { 
              System.out.print(node.data); 
              System.out.println(""); 
              return; 
          } 
  
          // Recur for left and right subtrees 
          printkdistanceNodeDown(node.left, k - 1); 
          printkdistanceNodeDown(node.right, k - 1); 
      } 
  
      int printkdistanceNode(Node node, Node target, int k)  
      { 
          if (node == null) 
              return -1; 
  
          if (node == target)  
          { 
              printkdistanceNodeDown(node, k); 
              return 0; 
          } 
  
          // Recur for left subtree 
          int dl = printkdistanceNode(node.left, target, k); 
  
          // Check if target node was found in left subtree 
          if (dl != -1)  
          { 
  
              if (dl + 1 == k)  
              { 
                  System.out.print(node.data); 
                  System.out.println(""); 
              } 
  
              else
                  printkdistanceNodeDown(node.right, k - dl - 2); 
  
              // Add 1 to the distance and return value for parent calls 
              return 1 + dl; 
          } 
  
          // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE 
          // Note that we reach here only when node was not found in left  
          // subtree 
          int dr = printkdistanceNode(node.right, target, k); 
          if (dr != -1)  
          { 
              if (dr + 1 == k)  
              { 
                  System.out.print(node.data); 
                  System.out.println(""); 
              }  
              else 
                  printkdistanceNodeDown(node.left, k - dr - 2); 
              return 1 + dr; 
          } 
  
          // If target was neither present in left nor in right subtree 
          return -1; 
      }
  </code></pre>