Second Minimum Node In a Binary Tree — LeetCode 671 Python Solution
- Problem
- #671
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
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
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.