采用 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; };