• Leetcode 515 每个树行中的最大值 BFS


     

      采用 BFS 算法逐行遍历,JAVA 解法:

        public final List<Integer> largestValues(TreeNode root) {
            List<Integer> reList = new LinkedList<Integer>();
            if (root == null) return reList;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            while (!queue.isEmpty()) {
                int currentSize = queue.size();
                int currentMax = Integer.MIN_VALUE;
                for (int i = 0; i < currentSize; i++) {
                    TreeNode node = queue.poll();
                    currentMax = Math.max(currentMax, node.val);
                    if (node.left != null) queue.add(node.left);
                    if (node.right != null) queue.add(node.right);
                }
                reList.add(currentMax);
            }
            return reList;
        }

      JS 解法:

    /**
     * Definition for a binary tree node.
     * function TreeNode(val, left, right) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.left = (left===undefined ? null : left)
     *     this.right = (right===undefined ? null : right)
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number[]}
     */
    var largestValues = function (root) {
        if (!root) return [];
        let reList = [];
        let nodeList = [];
        nodeList.push(root);
        while (nodeList.length > 0) {
            let currentMax = -Number.MAX_VALUE;
            let currentSize = nodeList.length;
            for (let i = 0; i < currentSize; i++) {
                let node = nodeList.shift();
                currentMax = currentMax > node.val ? currentMax : node.val;
                if (node.left) nodeList.push(node.left);
                if (node.right) nodeList.push(node.right);
            }
            reList.push(currentMax);
        }
        return reList;
    };

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    SpringBoot中添加事务
    隐藏样式
    Mybatis配置解析
    题目1064:反序数------玩转小聪明
    题目1063:整数和
    题目1062:分段函数23333333333333
    题目1060:完数VS盈数------这题做得我想骂人
    题目1059:abc----------就喜欢这样的题
    题目1050:完数-----------runtime error的问题
    题目1049:字符串去特定字符
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13941919.html
Copyright © 2020-2023  润新知