m2skills

nodes at k python

Jun 4th, 2018
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to print the nodes at distance K from a given node in binary tree
  3. # node class
  4. class node:
  5.     def __init__(self, element):
  6.         self.data = element
  7.         self.left = None
  8.         self.right = None
  9.  
  10.  
  11. # function to print child nodes at a distance k from the given node
  12. def print_nodes_at_K(root, K):
  13.     if root is None or K < 0:
  14.         return
  15.  
  16.     if K == 0:
  17.         print(root.data, end=" ")
  18.  
  19.     if K > -1:
  20.         print_nodes_at_K(root.left, K - 1)
  21.         print_nodes_at_K(root.right, K - 1)
  22.  
  23.  
  24.  
  25. head = node(1)
  26. head.left = node(2)
  27. head.right = node(3)
  28. head.left.left = node(4)
  29. head.left.right = node(5)
  30. head.right.right = node(6)
  31. head.left.left.right = node(7)
  32. head.right.right.left = node(8)
  33. head.left.left.right.left = node(9)
  34. head.left.left.right.left.left = node(10)
  35. head.right.right.left.right = node(11)
  36. print("Nodes at distance 2 from the root node are : ")
  37. print_nodes_at_K(head, 2)
Add Comment
Please, Sign In to add comment