LeetCode -- 515、654 题解

515:Find Largest 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:Maximum 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
}

两道题都是递归的解题方法,思路比较简单。

你可能感兴趣的:(JavaScript,leetcode)