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

Posted Push your limit!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[GeeksForGeeks] Print leftmost and rightmost nodes at each level of a binary tree.相关的知识,希望对你有一定的参考价值。

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.的主要内容,如果未能解决你的问题,请参考以下文章

回溯和递归澄清

素数,帮助理解平方根的使用

LEF 格式

为啥这段代码在 leetcode 运行良好,但在 geeksforgeeks 出现分段错误?

GeeksForGeeks 翻译计划

geeksforgeeks@ Equal to product (Binary Search)