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, 但是不存在第二小的值。
 

提示:

树中节点数目在范围 [1, 25] 内
1 <= Node.val <= 231 - 1
对于树中每个节点 root.val == min(root.left.val, root.right.val)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

# 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 preorderTraversal(self, root):
        if not root:return []
        stack, res = [root], []
        while stack:
            root = stack.pop()
            if root:
                res.append(root.val)
                if root.right:
                    stack.append(root.right)
                if root.left:
                    stack.append(root.left)
        return res
    def findSecondMinimumValue(self, root: TreeNode) -> int:
        nodes=sorted(list(set(self.preorderTraversal(root))))
        return nodes[1] if len(nodes)>1 else -1

# 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:
        if not root or not root.left and not root.right:return -1
        left=root.left.val
        right=root.right.val
        if left==root.val:
            left=self.findSecondMinimumValue(root.left)
        if right==root.val:
            right=self.findSecondMinimumValue(root.right)
        if left!=-1 and right!=-1:return min(left,right)
        elif left!=-1:
            return left
        else:
            return right

# 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:
        def helper(root,value):
            if not root:
                return -1
            if root.val>value:
                return root.val
            left=helper(root.left,value)
            right=helper(root.right,value)
            if left>value and right>value:
                return min(left,right)
            return max(left,right)
        return helper(root,root.val)

原文地址:https://www.cnblogs.com/xxxsans/p/14039284.html