Print leftmost and rightmost nodes of a Binary Tree | Python3 program to print corner node at each level of binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; Function to print corner node at each level ; If the root is null then simply return ; star node is for keeping track of levels ; pushing root node and star node ; Do level order traversal using a single queue ; n denotes the size of the current level in the queue ; If it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; Driver Code
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printCorner ( root : Node ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE q . append ( root ) NEW_LINE while q : NEW_LINE INDENT n = len ( q ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . popleft ( ) NEW_LINE if i == 0 or i == n - 1 : NEW_LINE INDENT print ( temp . key , end = " ▁ " ) NEW_LINE DEDENT if temp . left : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 10 ) NEW_LINE root . right = Node ( 20 ) NEW_LINE root . left . left = Node ( 8 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 16 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE printCorner ( root ) NEW_LINE DEDENT