Binary Tree Right Side View

本文介绍了一种解决特定二叉树问题的方法——获取二叉树从顶部到底部的右侧视图。通过层次遍历的方式,实现了有效地找出每层最右侧节点的值。

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

You should return [1, 3, 4].

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

很简单的一道题,题目要求是,假如站在树的右侧,那么可以看到哪些元素,意思就是记录每一层最右边的元素。所以很自然想到了层次遍历,这样可以对每一层都单独处理。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //利用层次遍历,然后每一层最后进入队列的就是右边可以看到的
        int count = 0;//记录每一层的元素数;
        List<Integer> list = new ArrayList<Integer>();//记录看到的元素
        Queue<TreeNode> queue = new LinkedList<TreeNode>();//队列,进行遍历使用
        if(root == null){
            return list;
        }
        count++;
        queue.offer(root);
        while(true){
            int next = 0;//记录下一层的元素数
            while(count > 0){//将本层的元素移除队列,同时将下一层的元素加入队列
                TreeNode tmp = queue.poll();//移除队首元素
                count--;
                if(count == 0){//count层的最后一个元素
                    list.add(tmp.val);
                }
                if(tmp.left != null){//左子树不空
                    queue.offer(tmp.left);
                    next++;
                }
                if(tmp.right != null){
                    queue.offer(tmp.right);
                    next++;
                }
            }
            if(next == 0){//如果队列为空,则遍历完毕
                break;
            }else{
                count = next;//更新为下一层的元素数
            }
        }
        return list;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值