zoukankan      html  css  js  c++  java
  • leetcode------Binary Tree Right Side View

    标题: Binary Tree Right Side View
    通过率: 27.9%
    难度: 中等

    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].

     本题就是个按层次遍历的一种延伸,按层遍历时每次讲每一层的最后一个元素放入结果的list中即可,代码如下:

     1 /**
     2  * Definition for binary tree
     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 ArrayList<Integer> rightSideView(TreeNode root) {
    12         ArrayList<Integer> res=new ArrayList<Integer>();
    13         LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
    14         int count=1,tmp=0;
    15         if(root==null)return res;
    16         queue.addLast(root);
    17         while(!queue.isEmpty()){
    18             tmp=0;
    19             for(int i=1;i<=count;i++){
    20                 TreeNode tmptree=queue.removeFirst();
    21                 if(i==count)res.add(tmptree.val);
    22                 if(tmptree.left!=null){
    23                     queue.addLast(tmptree.left);
    24                     tmp++;
    25                 }
    26                 if(tmptree.right!=null){
    27                     queue.addLast(tmptree.right);
    28                     tmp++;
    29                 }
    30                 
    31             }
    32             count=tmp;
    33         }
    34         return res;
    35     }
    36 }
  • 相关阅读:
    html5---音频视频基础一
    SQL--数据库性能优化详解
    微信--入门开发
    MVC----基础
    jquery -----简单分页
    sql优化
    集合的总结
    java并发编程与高并发解决方案
    java中boolean类型占几个字节
    正则表达式小结
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4395999.html
Copyright © 2011-2022 走看看