199. Binary Tree Right Side View

栏目: 数据库 · 发布时间: 6年前

内容简介: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.Example:难度: medium

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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

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

难度: medium

题目: 给定二叉树,想像一下你站在树的右边,返回能看到的所有结点,结点从上到下输出。

思路:层次遍历,BFS

Runtime: 1 ms, faster than 79.74% of Java online submissions for Binary Tree Right Side View.

Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Binary Tree Right Side View.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (null == root) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int qSize = queue.size();
            for (int i = 0; i < qSize; i++) {
                TreeNode node = queue.poll();
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (0 == i) {
                    result.add(node.val);
                }
            }
        }
        
        return result;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法统治世界——智能经济的隐形秩序

算法统治世界——智能经济的隐形秩序

徐恪、李沁 / 清华大学出版社有限公司 / 2017-11-15 / CNY 69.00

今天,互联网已经彻底改变了经济系统的运行方式,经济增长的决定性要素已经从物质资料的增加转变成为信息的增长。但是,只有信息的快速增长是不够的,这些增长的信息还必须是“有序”的。只有“有序”才能使信息具有价值,能够为人所用,能够指导我们实现商业的新路径。这种包含在信息里的隐形秩序才是今天信息世界的真正价值所在。经济系统的运行确实是纷繁复杂的,但因为算法的存在,这一切变得有律可循,算法也成为新经济系统里......一起来看看 《算法统治世界——智能经济的隐形秩序》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具