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

难度: medium

题目: 给定二叉树,想像一下你站在树的右边,返回能看到的所有结点,结点从上到下输出。

思路:层次遍历,BFS

Runtime: 1 ms, faster than 79.74% of Java online submissions for Binary Tree Right Side View.
Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Binary Tree Right Side View.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (null == root) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int qSize = queue.size();
            for (int i = 0; i < qSize; i++) {
                TreeNode node = queue.poll();
                if (node.right != null) {
                    queue.add(node.right);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (0 == i) {
                    result.add(node.val);
                }
            }
        }
        
        return result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018147683
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞