C++ BFS easy to understand


  • 0
    K

    The basic idea is to get the last node of each level in the tree. Using the BFS can help us easily reach this goal.

    /**
     * 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) {
            vector<int> res;
            if(!root) return res;
            queue<TreeNode*> q;
            q.push(root);
            while(q.size())
            {
                int n = q.size();
                TreeNode* top;
                for(int i = 0; i < n; ++i)
                {
                    top = q.front();
                    q.pop();
                    if(top->left) q.push(top->left);
                    if(top->right) q.push(top->right);
                }
                res.push_back(top->val);
            }
            
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.