EasyNo. 0671

Second Minimum Node In a Binary Tree — LeetCode 671 Python Solution

Topics
Tree, Depth-First Search, Binary Tree
Reading time
3 min

The problem

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.

Example

Input
root = [2,2,5,null,null,5,7]
Output
5
Explanation
The smallest value is 2, the second smallest value is 5.

Python solution

PythonSolution
# 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: Optional[TreeNode]) -> int:
        def dfs(root):
            if root:
                dfs(root.left)
                dfs(root.right)
                nonlocal ans, v
                if root.val > v:
                    ans = root.val if ans == -1 else min(ans, root.val)

        ans, v = -1, root.val
        dfs(root)
        return ans

Complexity

Time
O(V+E)
Space · auxiliary
O(V)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 671. Second Minimum Node In a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0669Trim a Binary Search TreeMedium
0662Maximum Width of Binary TreeMedium
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy

Frequently asked questions

How hard is LeetCode 671. Second Minimum Node In a Binary Tree?

LeetCode 671. Second Minimum Node In a Binary Tree is rated Easy on LeetCode.

What is the time complexity of LeetCode 671. Second Minimum Node In a Binary Tree?

The Python solution on this page runs in O(V+E).

What is the space complexity of LeetCode 671. Second Minimum Node In a Binary Tree?

The Python solution on this page uses O(V) auxiliary space.

What topics does LeetCode 671. Second Minimum Node In a Binary Tree cover?

LeetCode 671. Second Minimum Node In a Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.