美文网首页
671. Second Minimum Node In a Bi

671. Second Minimum Node In a Bi

作者: DrunkPian0 | 来源:发表于2017-09-08 22:45 被阅读9次

    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.

    这题我提交了几次没过最后用了普通dfs然后记录最小和次小节点混过去了。
    今天看了答案,有两种比较好的方法:

    1

    根节点肯定是最小的,那
    if node.val == 根节点val,继续找他的左右孩子
    else 返回这个节点的val,因为这个节点的val肯定是这棵树最小的val。
    https://discuss.leetcode.com/topic/102027/c-dfs-recursion

    2

    用一个set,然后preorder遍历这棵树,这个set里的第二个元素就是要找的元素。
    https://discuss.leetcode.com/topic/102163/very-simple-java-solution

    image.png

    相关文章

      网友评论

          本文标题:671. Second Minimum Node In a Bi

          本文链接:https://www.haomeiwen.com/subject/obnnjxtx.html