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

    其实就是层序遍历 的每层的最后一个元素!!!!

     1 class Solution {
     2     
     3     public List<Integer> rightSideView(TreeNode root) {
     4         List<Integer> res = new ArrayList<Integer>();
     5         Queue<TreeNode> queue = new LinkedList<TreeNode>();
     6         if(root==null) return res;
     7         queue.offer(root);
     8         int level_num = 1;
     9         while (!queue.isEmpty()) {
    10             level_num = queue.size();
    11             for(int i = 0; i < level_num; i++){
    12                 TreeNode node = queue.poll();
    13                 if(i==level_num-1)
    14                     res.add(node.val);
    15                 if(node.left != null) queue.offer(node.left);
    16                 if(node.right != null) queue.offer(node.right);
    17                 
    18             }
    19         }
    20         return res;
    21     }
    22 }
  • 相关阅读:
    第十二章类的无参方法
    第十三章人机猜拳
    第十一章类和对象
    面向对象七大原则。
    深入类的方法。
    使用集合组织相关数据。
    .NET框架
    C#数据类型
    错误。
    实现Windows的数据绑定
  • 原文地址:https://www.cnblogs.com/zle1992/p/8398387.html
Copyright © 2011-2022 走看看