Print the Nodes at the given distance K from the given Node in Python

Our task is to Print the Nodes at the given distance K from the given Node in Python.

In Python, we can make use of the inbuild modules of the tree to do this task.

But I use the basic method to do this to make sure that this will clear all your doubts.

Because if you are left with any of the doubts then it will be difficult for you to apply implement in other tree questions.

In this, we are going to make use of the recursion, class, and object.

Before going to the solution first get the basic knowledge about class and object.

Approach:-

  • First, make a recursive function that prints the node at the given distance.

Here is the code for that

def printkdistance(root,k): 
    if root is None or k< 0 : 
        return 
    if k==0: 
        print(root.data) 
        return 
    printkDistance(root.left,k-1) 
    printkDistance(root.right,k-1)
  • Now make a recursive function that will take the root node to the target node and pass that target node with the given distance in the above-made function.

Here is the code for this:-

def printkdistancenode(root,target,k): 
    if root is None: 
        return -1
    if root==target: 
        printkDistance(root,k) 
        return 0
    d=printkdistancenode(root.left,target,k)  
    if d!=-1: 
        if d+1==k : 
            print(root.data) 
        else: 
            printkdistance(root.right,k-dl-2) 
        return 1+d  
    dr=printkdistancenode(root.right,target,k) 
    if dr!=-1: 
        if dr+1==k: 
            print(root.data) 
        else: 
            printkdistance(root.left,k-dr-2) 
        return 1+dr 
    return -1

Here is the driver code:-

# Driver program to test above function 
root = Node(89) 
root.left = Node(8) 
root.right = Node(23) 
root.left.left = Node(86) 
root.left.right = Node(10) 
root.left.right.left = Node(102) 
root.left.right.right = Node(14) 
targetnode=root.left.left
print("The tree is shown:-")
display(root)
print("These are the nodes from given target node")
printkDistanceNode(root,targetnode,2) 
# By SHRIMAD

Output:-

Print the Nodes at the given distance K from the given Node in Python

Leave a Reply

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