Binary tree level order traversal with deque in C++


  • 0
    class Solution
    {
    public:
        std::vector<int> rightSideView(TreeNode *root)
        {
            std::vector<int> result;
            if (root == NULL)
            {
                return result;
            }
            std::deque<TreeNode *> nodes;
            nodes.push_back(root);
            int val;
            while (!nodes.empty())
            {
                std::size_t count = nodes.size();
                for (std::size_t i = 0; i != count; ++i)
                {
                    root = nodes.front();
                    val = root->val;
                    if (root->left != NULL)
                    {
                        nodes.push_back(root->left);
                    }
                    if (root->right != NULL)
                    {
                        nodes.push_back(root->right);
                    }
                    nodes.pop_front();
                }
                result.push_back(val);
            }
            return result;
        }
    };

Log in to reply
 

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