树:
2<br /> / \<br /> 2 5<br /> / \<br /> 5 7
0 一开始: dfs(root, 2),这里根节点值是2, 不比2大,因此递归调用在左子树,右子树上面。
11 第一层左子树:dfs(root, 2),与01同样的情况, 因此调用在它的左右子树。
111 dfs(nil, 2), 左子树为空,返回-1
112 dfs(nil, 2), 右子树为空,返回-1
11 回到这个递归分支,返回-1,表示左子树没找到。返回0
21 第一层右子树des(root, 2), 这里5比2大,直接返回5,分支结束。
0 左分支返回-1, 又分支返回5,递归结果返回5。递归结束。
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func findSecondMinimumValue(root *TreeNode) int {
return dfs(root, root.Val)
}
func dfs(root *TreeNode, s int) int {
// If root is nil, that means we can't find anything,
// we return -1
if root == nil {
return -1
}
// If the current tree value is bigger than the smallest
// element we hat, that means we have found the second smallest
// one in the tree, since all subtrees is greater or equal to this
// value.
if root.Val > s {
return root.Val
}
sLeft := dfs(root.Left, s)
sRight := dfs(root.Right, s)
if sLeft == -1 {
return sRight
}
if sRight == -1 {
return sLeft
}
return min(sLeft, sRight)
}
func min(a, b int) int {
if a < b {
return a
}
return b
}