199. 二叉树的右视图

题目链接

解题思路:

使用层序遍历,输出每一层最右边的节点即可。

C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(root);
        vector<int> rightView;
        if (root == nullptr) return rightView;

        while (!nodeQueue.empty()) {
            int size = nodeQueue.size();
            rightView.push_back(nodeQueue.front()->val);
            for (int i = 0; i < size; ++i) {
                auto node = nodeQueue.front();
                nodeQueue.pop();
                if (node->right) {
                    nodeQueue.push(node->right);
                }
                if (node->left) {
                    nodeQueue.push(node->left);
                }
            }
        }

        return rightView;
    }
};

 

posted @ 2021-04-02 15:46  洗盏更酌  Views(68)  Comments(0Edit  收藏  举报