C++ BFS method


  • 0
    class Solution {
    public:
        
        int findBottomLeftValue(TreeNode* root) {
            if (root->left == nullptr && root->right == nullptr)
            {
                return root->val;
            }
    
            vector<TreeNode*> parentList;
            vector<TreeNode*> childrenList;
            int result = 0;
    
            parentList.push_back(root);
    
            while (parentList.size() > 0)
            {
                TreeNode* parent = parentList[0];
                parentList.erase(parentList.begin());
    
                if (parent->left != nullptr)
                {
                    childrenList.push_back(parent->left);
                }
    
                if (parent->right != nullptr)
                {
                    childrenList.push_back(parent->right);
                }
    
                if (parentList.size() == 0 && childrenList.size() > 0)
                {
                    parentList = childrenList;
                    result = childrenList[0]->val;
                    childrenList.clear();
                }
            }
    
            return result;
        }
    };
    

Log in to reply
 

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