leetcode

我的 leetcode 题解(JavaScript)


/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var rob1 = function(root) {
  if (root === null) {
    return 0;
  }
  var val = 0;
  if (root.left !== null) {
    val = val + rob(root.left.left) + rob(root.left.right);
  }
  if (root.right !== null) {
    val = val + rob(root.right.left) + rob(root.right.right);
  }
  return Math.max(val + root.val, rob(root.left) + rob(root.right));
};

const rob2 = function(root) {
  const res = robsub(root);
  return Math.max(res[0], res[1]);
};
const robsub = function(root) {
  if (root === null) {
    return [0, 0];
  }
  const left = robsub(root.left);
  const right = robsub(root.right);
  let res = [0, 0];
  res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
  res[1] = root.val + left[0] + right[0];
  return res;
}