leetcode(671):Second Minimum Node In a Binary Tree

题目:
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.

Example 1:
Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

题目分析:
做这类题目首先要读懂题目,要审清楚题目,注意树的特殊的性质,然后从根节点开始,然后思考什么情况下怎么处理,然后利用递归,最终得解。

python代码:

class Solution(object):
    def findSecondMinimumValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root.left == None and root.right == None:
            return -1
        if root.left.val != root.val and root.right.val != root.val:
            return min(root.left.val, root.right.val)    
        if root.left.val == root.val and root.right.val == root.val:
            a = self.findSecondMinimumValue(root.left)
            b = self.findSecondMinimumValue(root.right)
            if a != -1 and b != -1:
                return min(a, b)
            if a == -1:
                return b
            if b == -1:
                return a
            return -1
        if root.left.val == root.val:
            a = self.findSecondMinimumValue(root.left)
            if a == -1:
                return root.right.val
            return min(a, root.right.val)
        if root.right.val == root.val:
            a = self.findSecondMinimumValue(root.right)
            if a == -1:
                return root.left.val
            return min(a, root.left.val)

大佬们的代码:

class Solution(object):
    def findSecondMinimumValue(self, root):
        res = [float('inf')]
        def traverse(node):
            if not node:
                return
            if root.val < node.val < res[0]:
                res[0] = node.val
            traverse(node.left)
            traverse(node.right)
        traverse(root)
        return -1 if res[0] == float('inf') else res[0]
def findSecondMinimumValue(self, root):
    self.ans = float('inf')
    min1 = root.val

    def dfs(node):
        if node:
            if min1 < node.val < self.ans:
                self.ans = node.val
            elif node.val == min1:
                dfs(node.left)
                dfs(node.right)

    dfs(root)
    return self.ans if self.ans < float('inf') else -1

要学习大佬们得写法呀·~~简洁易懂也是很重要的呢。

猜你喜欢

转载自blog.csdn.net/angela2016/article/details/79489307