力扣199. 二叉树的右视图

广度优先搜索

  • 思路:
    • 使用广度优先搜索,那么每层最后一次遍历的节点就是最右视图的节点;
    • 广度优先搜索模板:
      • std::queue nq;
        nq.push(root);
        
        while (!nq.empty()) {
            int levelSize = nq.size();
                    
            // deal with every layer
            for (int idx = 0; idx < levelSize; ++idx) {
                auto node = nq.front();
                nq.pop();
        
                
                /// do something
                // if (idx == levelSize - 1) {
                //     result.push_back(node->val);
                // }
        
                if (node->left) {
                    nq.push(node->left);
                }
                if (node->right) {
                    nq.push(node->right);
                }
            }
        }

  • 完整代码:
/**
 * 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 rightSideView(TreeNode* root) {
        std::vector result;
        if (root == nullptr) {
            return result;
        }

        std::queue nq;
        nq.push(root);

        while (!nq.empty()) {
            int levelSize = nq.size();
            
            for (int idx = 0; idx < levelSize; ++idx) {
                auto node = nq.front();
                nq.pop();

                if (idx == levelSize - 1) {
                    result.push_back(node->val);
                }

                if (node->left) {
                    nq.push(node->left);
                }
                if (node->right) {
                    nq.push(node->right);
                }
            }
        }

        return result;
    }
};

你可能感兴趣的:(力扣实践,leetcode,算法,职场和发展)