865. Smallest Subtree with all the Deepest Nodes [JavaScript]

一、题目

  Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

  A node is deepest if it has the largest depth possible among any node in the entire tree.

  The subtree of a node is that node, plus the set of all descendants of that node.

  Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

二、题目大意

  找出包含所有最深节点的根节点,最深节点的定义:该节点距离二叉树根节点的距离最长。

三、解题思路

  首先找最深节点的问题可以转化为求解二叉树高度的问题,有了高度信息之后,就会产生以下两种情况:

  • 当前根节点的左右子树一样高,那么就返回当前根节点。
  • 当前根节点的左右子树不一样高,那么返回相对较高的子树的根节点。

  经过递归处理之后,得到最终的答案。

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

  return help(root)[1]

  function help (root) {
    if (!root) {
      return [-1, null]
    }
    const l = help(root.left)
    const r = help(root.right)

    const lHeight = l[0]
    const rHeight = r[0]

    const h = Math.max(rHeight, lHeight) + 1

    const v = lHeight === rHeight ? root : (lHeight > rHeight ? l[1] : r[1])

    return [h, v]
  }
}

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值