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

    Top view, Bot view, right view, and left view.

     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> result = new ArrayList<Integer>();
    13         if(root == null) return result;
    14         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
    15         queue.add(root);
    16         queue.add(null);
    17         int level = 0;
    18         while(queue.size() != 1){
    19             TreeNode tmp = queue.poll();
    20             if(tmp == null){
    21                 queue.add(null);
    22                 level ++;
    23             }else{
    24                 if(result.size() == level){
    25                     result.add(tmp.val);
    26                 }else{
    27                     result.set(level,tmp.val);
    28                 }
    29                 if(tmp.left != null)queue.add(tmp.left);
    30                 if(tmp.right != null)queue.add(tmp.right);
    31             }
    32         }
    33         return result;
    34     } 
    35 }
  • 相关阅读:
    java 测试 (junit+ junit 断言 + postman)
    junit 运行(eclipse + IDEA)
    junit 常用注解 + junit 断言详解
    工作周报模板
    spring boot tomcat 部署
    spring boot 集成JSP
    spring boot 集成 Mybatis,JPA
    JPA 常用注解
    员工年终绩效考核表模板
    2013 Noip提高组 Day1
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4395346.html
Copyright © 2011-2022 走看看