671. 二叉树中第二小的节点

给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么该节点的值等于两个子节点中较小的一个。

更正式地说,root.val = min(root.left.val, root.right.val) 总成立。

给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。

 

示例 1:

输入:root = [2,2,5,null,null,5,7]
输出:5
解释:最小的值是 2 ,第二小的值是 5 。

示例 2:

输入:root = [2,2,2]
输出:-1
解释:最小的值是 2, 但是不存在第二小的值。

 

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findSecondMinimumValue = function(root) {
    let arr = new Array()
    arr.push(root)
    let res = -1
    while(arr.length){
        let cur = arr.shift()
        if(cur.val > root.val){
            res = res == -1 ? cur.val : Math.min(res, cur.val)
        }
        if(cur.left) arr.push(cur.left)
        if(cur.right) arr.push(cur.right)
    }
    return res
};

 Python3

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findSecondMinimumValue(self, root: TreeNode) -> int:
      nodeList = list()
      nodeList.append(root)
      res = -1
      while len(nodeList) > 0:
        cur = nodeList[0]
        if cur.val > root.val:
          res = cur.val if res == -1 else min(res, cur.val)
        del nodeList[0]
        if cur.left is not None:
          nodeList.append(cur.left)
        if cur.right is not None:
          nodeList.append(cur.right)
      return res        

 

提示:

  • 树中节点数目在范围 [1, 25] 内
  • 1 <= Node.val <= 231 - 1
  • 对于树中每个节点 root.val == min(root.left.val, root.right.val)
posted @ 2021-07-27 09:44  尖子  阅读(27)  评论(0编辑  收藏  举报