513. 找树左下角的值

2020-08-17  本文已影响0人  来到了没有知识的荒原

层序遍历,每次保存上一层的信息
如果当前层(q2队列中)没有元素了,q1中保存的就是最后一层


class Solution {
public:
    
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*>q1,q2;
        q2.push(root);
        
        while(q2.size()){
            q1=q2;
            int len=q2.size();
            while(len--){
                auto u=q2.front();
                q2.pop();
                if(u->left)q2.push(u->left);
                if(u->right)q2.push(u->right);
            }
        }
        return q1.front()->val;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读