Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to print the nodes at distance K from a given node in binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to print child nodes at a distance k from the given node
- def print_nodes_at_K(root, K):
- if root is None or K < 0:
- return
- if K == 0:
- print(root.data, end=" ")
- if K > -1:
- print_nodes_at_K(root.left, K - 1)
- print_nodes_at_K(root.right, K - 1)
- head = node(1)
- head.left = node(2)
- head.right = node(3)
- head.left.left = node(4)
- head.left.right = node(5)
- head.right.right = node(6)
- head.left.left.right = node(7)
- head.right.right.left = node(8)
- head.left.left.right.left = node(9)
- head.left.left.right.left.left = node(10)
- head.right.right.left.right = node(11)
- print("Nodes at distance 2 from the root node are : ")
- print_nodes_at_K(head, 2)
Add Comment
Please, Sign In to add comment