zoukankan      html  css  js  c++  java
  • [leedcode 199] 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].

    /**
     * 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) {
            //层序遍历,每次获取每一层最后的节点,并将其保存在结果
            LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
            List<Integer> res=new ArrayList<Integer>();
            if(root==null) return res;
            queue.add(root);
            while(!queue.isEmpty()){
                int count=queue.size();
                res.add(queue.get(count-1).val);
                for(int i=0;i<count;i++){
                    TreeNode temp=queue.remove();
                    if(temp.left!=null)
                    queue.add(temp.left);
                    if(temp.right!=null)
                    queue.add(temp.right);
                }
            }
            return res;
        }
    }
  • 相关阅读:
    Java之lambda表达式
    修改IntelliJ IDEA的java编译版本
    no route to host解决方案、Failed to start LSB: Bring up/down networking的问题解决方案
    spark转换集合为RDD
    spark编写word count
    nexus
    spark 源码安装
    spark shell
    maven
    git
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4700367.html
Copyright © 2011-2022 走看看