Leetcode
  • Leetcode Questions
  • Runtime Screenshots
  • DataStructure
    • Leetcode 394. Decode String
    • Leetcode 225. Implement Stack Using Queues
    • Leetcode 336. Palindrome Pairs
    • Leetcode 316. Remove Duplicate Letters
    • Leetcode 206. Reverse Linked List
    • Leetcode 347. Top K Frequent Elements
    • Leetcode 227. Basic Calculator II
    • Leetcode 224. Basic Calculator
  • Linear
    • Leetcode 23. Merge k Sorted Lists
    • Leetcode 48. Rotate Image
    • Leetcode 6. ZigZag Conversion
    • Leetcode 438. Find All Anagrams in a String
    • Leetcode 189. Rotate Array
    • LeetCode 56. Merge Intervals
    • Leetcode 4. Median of Two Sorted Array
    • Leetcode 3. Longest Substring Without Repeating Characters
    • Leetcode 8. String to Integer (atoi)
    • Leetcode 5. Longest Palindromic Substring
    • Leetcode 11. Container With Most Water
  • Tree
    • Leetcode 103. Binary Tree Zigzag Level Order Traversal
    • Leetcode 508. Most Frequent Subtree Sum
    • Leetcode 226. Invert Binary Tree
    • Leetcode 222. Count Complete Tree Nodes
    • Leetcode 250. Count Univalue Subtrees
    • Leetcode 285. Inorder Successor in BST
    • Leetcode 230. Kth Smallest Element in a BST
    • Leetcode 543. Diameter of Binary Tree
    • Leetcode 199. Binary Tree Right Side View
  • Math
    • Leetcode 50. Power(x, n)
    • Leetcode 166. Fraction to Recurring Decimal
    • Leetcode 7. Reverse Integer
    • Leetcode 360. Sort Transformed Array
    • Leetcode 367. Valid Perfect Square
    • Leetcode 12. Integer to Roman
  • DynamicProgramming
    • Leetcode 10. Regular Expression Matching
    • Leetcode 253. Meeting Rooms II
    • Leetcode 303. Range Sum Query
    • Leetcode 22. Generate Parentheses
  • Graph
    • Leetcode 142. Linked List Cycle II
    • Leetcode 261. Graph Valid Tree
    • Leetcode 339. Nested List Weight Sum
    • Leetcode 207. Course Schedule
  • OODesign
    • Leetcode 295. Find Media From Data Stream
Powered by GitBook
On this page
  • 思路
  • 解答
  • Complexity Analysis
  • 拓展
  • 总结

Was this helpful?

  1. Tree

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

思路

我们发现right side view由每一层最右边的元素组成。鉴于此,我们可以对树进行level-order traversal,在访问每一层节点时, 取出最右边的元素放入返回答案列表。

为了按层遍历整个树,我们需要对基础的BFS做出修改。BFS会自动按层遍历整个数组,但是我们无法知道当前在哪一层。 因此,一个简单且巧妙的方法为记录每层节点数量,每次访问完这个数量的节点后,我们即可知道当前这层已经访问完成。

解答

/**
 * 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) {

        List<Integer> res = new LinkedList<Integer>();
        if (root == null) return res; 

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        while (! queue.isEmpty()) { 

            // get right most element in the current level
            int levelCount = queue.size();
            TreeNode rightmost = queue.getLast();
            res.add(rightmost.val);

            // only pop current level's elements from the queue
            for (int i = 0; i < levelCount; i++) {
                TreeNode node = queue.removeFirst();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }

        return res;
    }
}

Complexity Analysis

  • Time Complexity: O(n). 我们需要按层遍历所有n个节点。

  • Space Complexity: O(n). Queue中最多储存所有的O(n)个节点。

拓展

我们可以用类似的思想,实现left-side view吗?或者bottom-view?需要修改那一行(几行)代码?

总结

大量树这个类别的题目都在考察BFS,DFS算法的数量应用。我们要掌握它们的多种变体和常用的修改手段,比如这里的按层遍历。

PreviousLeetcode 543. Diameter of Binary TreeNextMath

Last updated 5 years ago

Was this helpful?