【LeetCode】199. Binary Tree Right Side View-二叉树右视图结点

一、描述:

二、思路:

输出二叉树右视图所有结点,即输出每一层的最后一结点;

水平面上,从右向左能看到的结点构成的图形,依次输出。原题样例二叉树中,右视图能看到的结点从上而下排成一列,依次是1-3-4;

以二叉树最大深度作为循环条件,使用Queue队列存储每一层的结点,并输出每一层最后一结点;

类似于LeetCode 513

三、代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> rightSideView(TreeNode root) {
12         List<Integer> list = new ArrayList<Integer>();
13         Queue<TreeNode> queue = new LinkedList<TreeNode>();
14         int depth = depth(root);
15         queue.offer(root);
16         while((depth--)>=1){
17             TreeNode node;
18             int size = queue.size();
19             for(int i=0;i<size;i++){
20                 if(i==size-1){  //判断是否为该层的最后一结点
21                     node = queue.peek();
22                     list.add(node.val);
23                 }
24                 node = queue.remove();
25                 if(node.left!=null){
26                     queue.offer(node.left);
27                 }
28                 if(node.right!=null){
29                     queue.offer(node.right);
30                 }
31             }
32         }
33         return list;
34     }
35     
36     public int depth(TreeNode root){    //求二叉树最大深度
37         if(root==null){
38             return 0;
39         }
40         if(root.left==null && root.right==null){
41             return 1;
42         }
43         int left = depth(root.left);
44         int right = depth(root.right);
45         return left<right ? right+1 : left+1;
46     }
47 }

 

转载于:https://www.cnblogs.com/WalkerSteve/p/6610192.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值