zoukankan      html  css  js  c++  java
  • 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 public List<Integer> rightSideView(TreeNode root) {
     2         List<Integer> res = new ArrayList<Integer>();
     3         if (root == null) {
     4             return res;
     5         }
     6         Queue<TreeNode> q = new LinkedList<TreeNode>();
     7         q.offer(root);
     8         while (!q.isEmpty()) {
     9             int size = q.size();
    10             for (int i = 0; i < size; i++) {
    11                 TreeNode cur = q.poll();
    12                 if (i == size - 1) {
    13                     res.add(cur.val);
    14                 }
    15                 if (cur.left != null) {
    16                     q.offer(cur.left);
    17                 }
    18                 if (cur.right != null) {
    19                     q.offer(cur.right);
    20                 }
    21             }
    22         }
    23         return res;
    24     }
  • 相关阅读:
    Paperfolding HDU
    I
    2020年8月11日第一次组队训练
    2018ICPC南京I. Magic Potion
    【贪心】纪念品分组
    【贪心】删数问题
    【排序】排名
    小X与队列
    B.T.B.F.
    2018浙江理工大学迎新赛——决赛
  • 原文地址:https://www.cnblogs.com/gonuts/p/4413375.html
Copyright © 2011-2022 走看看