Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to print child nodes at distance k from the given node
- #include <iostream>
- #include <queue>
- #include <map>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to print child nodes at a distance k from the given node
- void print_nodes_at_K(node* root, int K){
- if(root == NULL || K < 0){
- return;
- }
- if(K == 0){
- cout<<root->data<<" ";
- }
- if(K > -1) {
- print_nodes_at_K(root->left, K - 1);
- print_nodes_at_K(root->right, K - 1);
- }
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- head->hd = 0;
- cout<<"Nodes at distance 2 from the root node are : ";
- print_nodes_at_K(head, 2);
- }
- /*
- Nodes at distance 2 from the root node are : 4 5 6
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment