leetcode二叉树-1302. 层数最深叶子节点的和

考点 层序遍历


package binarytree.deepestLeavesSum;

import binarytree.untils.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 1302. 层数最深叶子节点的和
 * 给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
 * <p>
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * <p>
 * <p>
 * 输入:root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 * 输出:15
 * 示例 2:
 * <p>
 * 输入:root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
 * 输出:19
 * <p>
 * <p>
 * 提示:
 * <p>
 * 树中节点数目在范围 [1, 104] 之间。
 * 1 <= Node.val <= 100
 */
public class deepestLeavesSum {
    /**
     * 层序遍历
     * @param root
     * @return
     */
    public static int deepestLeavesSum(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        levelOrder(root, res);
        List<Integer> list = res.get(res.size() - 1);
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += list.get(i);
        }
        return sum;
    }

    private static List<List<Integer>> levelOrder(TreeNode root, List<List<Integer>> res) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode treeNode = queue.poll();
                if (treeNode.left != null) {
                    queue.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    queue.add(treeNode.right);
                }
                list.add(treeNode.val);
            }
            if (list.size() != 0) {
                res.add(list);
            }
        }
        return res;
    }
}

posted @ 2021-12-17 11:03  小傻孩丶儿  阅读(89)  评论(0编辑  收藏  举报