zoukankan      html  css  js  c++  java
  • LeetCode 199. Binary Tree Right Side View

    原题链接在这里:https://leetcode.com/problems/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]

    题解:

    Binary Tree Level Order Traversal相似,通过BFS一层一层扫树,这里是仅添加最右面的一个点,就是curCount = 1 的时候.

    Note: 当curCount == 0 时, curCount = nextCount, 不要忘记把nextCount归0.

    Time Complexity: O(n). n是tree的node总数.

    Space: O(n), que的大小.

    AC Java:

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution {
    11     public List<Integer> rightSideView(TreeNode root) {
    12         List<Integer> res = new ArrayList<Integer>();
    13         if(root == null){
    14             return res;
    15         }
    16         
    17         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
    18         que.add(root);
    19         int curCount = 1;
    20         int nextCount = 0;
    21         while(!que.isEmpty()){
    22             TreeNode cur = que.poll();
    23             curCount--;
    24             
    25             if(cur.left != null){
    26                 que.add(cur.left);
    27                 nextCount++;
    28             }
    29             if(cur.right != null){
    30                 que.add(cur.right);
    31                 nextCount++;
    32             }
    33             
    34             if(curCount == 0){
    35                 res.add(cur.val);
    36                 curCount = nextCount;
    37                 nextCount = 0;
    38             }
    39         }
    40         
    41         return res;
    42     }
    43 }
  • 相关阅读:
    MVC MVP MVVM
    RC4 对称加密
    ARM 寻址方式
    杂项记录 arm64 的一些特性
    无向图-笔记-代码
    iOS 自定义导航栏
    ios中设置UIButton圆角,添加边框
    iOS 中UICollectionView实现各种视觉效果
    UIScrollView中UITableView
    iOS 13 适配总结
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824977.html
Copyright © 2011-2022 走看看