zoukankan      html  css  js  c++  java
  • 0199. Binary Tree Right Side View (M)

    Binary Tree Right Side View (M)

    题目

    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.

    Example:

    Input: [1,2,3,null,5,null,4]
    Output: [1, 3, 4]
    Explanation:
    
       1            <---
     /   
    2     3         <---
          
      5     4       <---
    

    题意

    站在一个二叉树的右边向左看,求从上到下能看到的所有元素。

    思路

    相当于取每一行的最右元素,层序遍历即可。


    代码实现

    Java

    class Solution {
        public List<Integer> rightSideView(TreeNode root) {
            List<Integer> ans = new ArrayList<>();
            Queue<TreeNode> q = new LinkedList<>();
    
            if (root != null) {
                q.offer(root);
            }
    
            while (!q.isEmpty()) {
                int size = q.size();
                TreeNode cur = null;
                while (size > 0) {
                    cur = q.poll();
                    if (cur.left != null) q.offer(cur.left);
                    if (cur.right != null) q.offer(cur.right);
                    size--;
                }
                ans.add(cur.val);
            }
    
            return ans;
        }
    }
    
  • 相关阅读:
    对deferred(延迟对象)的理解
    string 、char* 、 char []的转换
    char* 和 cha[]
    层序遍历二叉树
    之字形打印二叉树
    右值
    函数指针(待修改)
    top k

    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/mapoos/p/14381925.html
Copyright © 2011-2022 走看看