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

本文介绍了一种使用队列实现的二叉树层级遍历算法,并特别关注每一层的最左侧和最右侧节点。通过Java实现的具体示例,展示了如何获取这些节点。

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 }

 

转载于:https://www.cnblogs.com/lz87/p/7277712.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值