跳转至

199.Binary Tree Right Side View

Tags: Medium Tree Depth-first Search Breadth-first Search

Links: https://leetcode.com/problems/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       <---

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!root) return {};

        queue<TreeNode *> q;
        q.push(root);
        vector<int> res;
        while (!q.empty()) {
            int n = q.size();
            for (int i = 0; i < n; ++i) {
                TreeNode *tmp = q.front(); q.pop();
                if (i == 0) res.push_back(tmp -> val);
                if (tmp -> right) q.push(tmp -> right);
                if (tmp -> left) q.push(tmp -> left);
            }
        }

        return res;
    }
};

二叉树的右视图,在纸上模拟发现其实就是层序遍历,每次把每一层的第一个元素推入结果数组即可,考察的只是一个思维转化的过程。