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

Example:

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

   1            <---
 /   
2     3         <---
      
  5     4       <---

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

知道是层遍历三部曲,不知道怎么变形

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

先左后右,第一个在左

先右后左,第一个在右

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

先左后右,第一个在左

先右后左,第一个在右

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

 [是否头一次写此类driver funcion的代码] :

 [潜台词] :

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //ini
        List<Integer> res = new ArrayList<Integer>();
        
        //cc
        if (root == null) return res;
        
        //bfs in 3 steps
        Queue<TreeNode> q = new LinkedList<>();
        
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
   
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                System.out.println("cur.val = " + cur.val);
                //add previously if it is from the last row
                if (i == 0) res.add(cur.val);
                
                if (cur.right != null) q.offer(cur.right);
                if (cur.left != null) q.offer(cur.left);
            }
        }

        //return
        return res;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/9390616.html