Skip to content

Instantly share code, notes, and snippets.

@ajinkyajawale14499
Created July 28, 2019 17:32
Show Gist options
  • Save ajinkyajawale14499/ec30f22a1ec67999ebf28de098327188 to your computer and use it in GitHub Desktop.
Save ajinkyajawale14499/ec30f22a1ec67999ebf28de098327188 to your computer and use it in GitHub Desktop.
Nodes at k distance from root of Binary Tree
//code goes here!
#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
using namespace std;
class Node
{
public:
int data;
Node* left;
Node* right;
Node(int data)
{
this->data=data;
this->left=NULL;
this->right=NULL;
}
};
void KDistanceBinaryTree(Node *root , int k)
{
if(root == NULL)
return;
if( k == 0 )
{
cout << root->data << " ";
return ;
}
else
{
KDistanceBinaryTree( root->left, k - 1 ) ;
KDistanceBinaryTree( root->right, k - 1 ) ;
}
}
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 8
*/
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(8);
KDistanceBinaryTree(root, 2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment