Given a Binary Tree, Print the corner nodes at each level. The node at the leftmost and the node at the rightmost.
For example, output for following is 8,.
Solution. Level Order traversal using queue.
Core idea:level order traversal always visit nodes the one level from left to right.
And we know the number of nodes at each level by pre-reading the size of the queue.
1 Importjava.util.ArrayList;2 Importjava.util.LinkedList;3 ImportJava.util.Queue;4 5 classTreeNode {6 TreeNode left;7 TreeNode right;8 intVal;9TreeNode (intval) {Ten This. left =NULL; One This. right =NULL; A This. val =Val; - } - } the Public classSolution { - PublicArraylist<treenode>getleftrightmostateachlevel (TreeNode root) { -arraylist<treenode> result =NewArraylist<treenode>(); - if(Root = =NULL){ + returnresult; - } +queue<treenode> queue =NewLinkedlist<treenode>(); A Queue.offer (root); at while(!Queue.isempty ()) { - intSize =queue.size (); - for(inti = 0; i < size; i++){ -TreeNode Curr =Queue.poll (); - if(i = = 0){ - Result.add (curr); in } - if(i > 0 && i = = size-1){ to Result.add (curr); + } - if(Curr.left! =NULL){ the Queue.offer (curr.left); * } $ if(Curr.right! =NULL){Panax Notoginseng Queue.offer (curr.right); - } the } + } A returnresult; the } +}
[Geeksforgeeks] Print leftmost and rightmost nodes at each level of a binary tree.