LeetCode 每日一题 1302. 层数最深叶子节点的和

题目链接

1302. 层数最深叶子节点的和

注意事项

要用非递归的方式求二叉树深度(即层次遍历BFS)

代码

class Solution {
public:
    int deepestLeavesSum(TreeNode* root) {

        vector> nodes;
        int sum = 0;
        int maxHeight = maxDeep(root, &nodes);

        for (int i = 0; i < nodes.size(); ++i) {
            if (maxHeight == nodes[i].second){
                sum += nodes[i].first;
            }
        }

        return sum;
    }

    int maxDeep(TreeNode* root, vector>* nodes){

        if (root == nullptr){
            return 0;
        }

        queue q;
        int depth = 0;

        q.push(root);
        while (!q.empty()){
            int cnt = 0;
            int currentNodes = q.size();
            depth++;

            while (cnt < currentNodes){
                bool f = true;
                TreeNode* treeNode = q.front();
                q.pop();

                if (treeNode->left != nullptr){
                    f = false;
                    q.push(treeNode->left);
                }

                if (treeNode->right != nullptr){
                    f = false;
                    q.push(treeNode->right);
                }

                if (f){
                    nodes->push_back({treeNode->val, depth});
                }

                cnt++;
            }
        }

        return depth;
    }
};

Original: https://www.cnblogs.com/shixuanliu/p/16628388.html
Author: deafl
Title: LeetCode 每日一题 1302. 层数最深叶子节点的和

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/587607/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球