[
tree
recursion
dfs
]
Leetcode 0671 Second Minimum Node In a Binary Tree
Problem statement
https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/
Solution
Just traverse our tree, using dfs or bfs.
Complexity
We have O(n)
time complexity and O(h)
space complexity.
Code
class Solution:
def findSecondMinimumValue(self, root):
self.found = float("inf")
rootval = root.val
def dfs(node):
if node.val == rootval:
if node.left: dfs(node.left)
if node.right: dfs(node.right)
else:
self.found = min(self.found, node.val)
dfs(root)
return self.found if self.found != float("inf") else -1