LeetCode--515、654題解


515:Find Larget Value in Each Tree Row
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var largestValues = function(root) {
  let level = 0;
  let result = [];
  recursive(root, level)
  return result

  function recursive(node, level){
    if(node === null) {
      return
    }
    if(result[level] == undefined || result[level] < node.val){
      result[level] = node.val
    }
    recursive(node.left, level + 1);
    recursive(node.right, level + 1);
  }
};
654:Maximm Binary Tree
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} nums
 * @return {TreeNode}
 */
var constructMaximumBinaryTree = function(array) {
  if (array.length === 0) {
    return null
  }
  let rootIndex = getMaxIndex(array);
  let node = new TreeNode(array[rootIndex]);
  node.left = constructMaximumBinaryTree(array.slice(0, rootIndex));
  node.right = constructMaximumBinaryTree(array.slice(rootIndex + 1, array.length));
  return node;
};

function getMaxIndex(array){
  let max = -Infinity;
  let maxIndex;
  array.forEach(function(item, index){
    if (item > max) {
      max = item
      maxIndex = index
    }
  })
  return maxIndex
}
二つの問題は再帰的な解法で、考え方は簡単です.