Loading

二叉树层序遍历模版

二叉树的层序遍历

该题为求最小深度

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == NULL) {
            return
        } 
        int dep = 0;
        queue <TreeNode*> que;
        que.push(root);
        while (!que.empty()) {
            dep ++;
            int flag = 0;
            int size = que.size();
            for (int i = 0; i < size; i ++) {
                TreeNode* node = que.front();
                que.pop();
                if (node -> left) que.push(node -> left);
                if (node -> right) que.push(node -> right);
                if (!node -> right && !node -> left) {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1) break;
        }
        return dep;
    }
};
posted @ 2022-04-20 09:17  Yueming-He  阅读(23)  评论(0编辑  收藏  举报