Easy C++ solution - Using level order traversal and queue


  • 0
    S

    The vectorr v saves only first items of each level

    int findBottomLeftValue(TreeNode* root) {
            queue<TreeNode*> q;
            queue<int> qLevel;
            int leftMember;
            int currentLevel=0;
            q.push(root);
            qLevel.push(0);
            while(!q.empty()){
                TreeNode *temp = new TreeNode(0);
                temp=q.front();
                q.pop();
                int level=qLevel.front();
                qLevel.pop();
                if(level>=currentLevel){
                    leftMember=temp->val;
                    currentLevel++;
                }
                if(temp->left!=NULL){
                    q.push(temp->left);
                    qLevel.push(level+1);
                }
                if(temp->right!=NULL){
                    q.push(temp->right);
                    qLevel.push(level+1);
                }
            }
            return leftMember;
        }
    

Log in to reply
 

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