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

    题解:

    这道题非常有趣,是找二叉树从右侧看的时候能看到的数,其实思路也是很简单,即返回每一层的最右边的一个数就好了,在二叉树的层序遍历的代码上稍作修改即可。对二叉树的层序遍历不太清楚的朋友,可看我之前的博客《二叉树完全总结》。具体没什么好说的,直接上代码:

     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 List<Integer> rightSideView(TreeNode root) {
    12         List<Integer> res = new ArrayList<Integer>();
    13         if(root==null)
    14             return res;
    15         Queue<TreeNode> Q = new LinkedList<TreeNode>(); 
    16         Q.offer(root);
    17         int curLevel = 1;
    18         res.add(root.val);
    19         while(!Q.isEmpty()){
    20             int levelSize = Q.size();
    21             int count = 0;
    22             TreeNode last = null;
    23             while(count<levelSize){
    24                 TreeNode p = Q.poll();
    25                 if(p.left!=null){
    26                     last = p.left;
    27                     Q.offer(p.left);
    28                 }
    29                 if(p.right!=null){
    30                     last = p.right;
    31                     Q.offer(p.right);
    32                 }
    33                 count++;
    34             }
    35             if(last!=null)
    36                 res.add(last.val);
    37             
    38         }
    39         return res;
    40     }
    41 }
  • 相关阅读:
    类操作工具类
    让你的Git水平更上一层楼的10个小贴士
    android camera(四):camera 驱动 GT2005
    android camera(三):camera V4L2 FIMC
    android camera(二):摄像头工作原理、s5PV310 摄像头接口(CAMIF)
    android camera(一):camera模组CMM介绍
    MTK Android Driver知识大全
    makefile 进阶
    RGB Bayer Color分析
    8.3 MPI
  • 原文地址:https://www.cnblogs.com/codershell/p/4396249.html
Copyright © 2011-2022 走看看