671. Second Minimum Node In a Binary Tree [JavaScript]

本文探讨了在特殊二叉树中寻找第二小值的问题,提供了两种解决方案:一是通过递归遍历并筛选,二是采用优化的递归方法直接定位第二小值。深入解析了算法细节,帮助读者理解并掌握这一经典数据结构问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、题目

  Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes.

  Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.

  If no such second minimum value exists, output -1 instead.

二、题目大意

 &esmp;找出二叉树中第二小的值,如果不存在返回-1。

三、解题思路

  最朴素的解法是通过递归遍历二叉树,再从获取到的数组中寻找第二小的值。

const findSecondMinimumValue = root => {
  const ans = []
  help(root)

  ans.sort((next, pre) => next - pre)

  const max = ans.length

  if (max <= 1) {
    return -1
  }

  let x = ans[0]

  for (let i = 1; i < max; i++) {
    const temp = ans[i]
    if (temp !== x) {
      return temp
    }
  }

  return -1

  function help (root) {
    if (!root) {
      return
    }
    ans.push(root.val)
    help(root.left)
    help(root.right)
  }
}

  社区中还有一种递归求解的方法

四、代码实现
const findSecondMinimumValue = root => {

  if (!root) {
    return -1
  }

  if (!root.left && !root.right) {
    return -1
  }

  let left = root.left.val
  let right = root.right.val

  if (root.left.val === root.val) {
    left = findSecondMinimumValue(root.left)
  }
  if (root.right.val === root.val) {
    right = findSecondMinimumValue(root.right)
  }

  if (left !== -1 && right !== -1) {
    return Math.min(left, right)
  } else if (left != -1) {
    return left
  } else {
    return right
  }
}

  如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

  您还可以在这些地方找到我:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值