Clear C++ Solution Using two Queue


  • 0
    L
    /**
     * 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 {
    private:
        queue<TreeNode *>  s1;
        queue<TreeNode *>  s2;
        queue<TreeNode *>  tmp;
    public:
        int findBottomLeftValue(TreeNode* root) {
            TreeNode* ret;
            s2.push(root);
            while (true) {
                // swap s1 s2
                tmp = s1;
                s1 = s2;
                s2 = tmp;
                ret = s1.front();
               // user s1 for loop
               while(!s1.empty()) {
                 TreeNode* e = s1.front();
                 s1.pop();
                 TreeNode* left = e->left;
                 TreeNode* right = e->right;
                 if (left != NULL) {
                    s2.push(left);
                 }
                 if (right != NULL) {
                    s2.push(right);
                }
             }
             
             // outer while end 
             if (s1.empty() && s2.empty()){
                   break;
             }
            }
            return ret->val;
        }
    };
    

Log in to reply
 

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