C++ BFS with right branch first


  • 0
    A

    Use a double ended queue to store the nodes, instead of pushing in left first, push in right node first, this was the left most node of the last row will always be the last node in the queue.

    class Solution {
    public:
        int findBottomLeftValue(TreeNode* root) {
            deque<TreeNode*> nodes;
            nodes.push_front(root);
            TreeNode* currentNode = nullptr;
            while(!nodes.empty())
            {
                currentNode = nodes.front();
                nodes.pop_front();
                if(currentNode->right)
                    nodes.push_back(currentNode->right);
                if(currentNode->left)
                    nodes.push_back(currentNode->left);
                
            }
            return currentNode->val;
        }
    };
    

Log in to reply
 

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