[GeeksForGeeks] Print leftmost and rightmost nodes at each level of a binary tree.

來源:互聯網
上載者:User

標籤:and   each   sem   log   get   public   width   add   always   

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 15, 10, 20, 8, 25.

 

Solution. Level Order Traversal using queue.

Core idea:  Level order traversal always visit nodes of 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 import java.util.ArrayList; 2 import java.util.LinkedList; 3 import java.util.Queue; 4  5 class TreeNode { 6     TreeNode left; 7     TreeNode right; 8     int val; 9     TreeNode(int val){10         this.left = null;11         this.right = null;12         this.val = val;13     }14 }15 public class Solution {16     public ArrayList<TreeNode> getLeftRightMostAtEachLevel(TreeNode root) {17         ArrayList<TreeNode> result = new ArrayList<TreeNode>();18         if(root == null){19             return result;20         }21         Queue<TreeNode> queue = new LinkedList<TreeNode>();22         queue.offer(root);        23         while(!queue.isEmpty()){24             int size = queue.size();25             for(int i = 0; i < size; i++){26                 TreeNode curr = queue.poll();27                 if(i == 0){28                     result.add(curr);29                 }30                 if(i > 0 && i == size - 1){31                     result.add(curr);32                 }33                 if(curr.left != null){34                     queue.offer(curr.left);35                 }36                 if(curr.right != null){37                     queue.offer(curr.right);38                 }39             }40         }41         return result;42     }43 }

 

[GeeksForGeeks] Print leftmost and rightmost nodes at each level of a binary tree.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.