图片.png
    树:

    1. 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。递归结束。

    1. type TreeNode struct {
    2. Val int
    3. Left *TreeNode
    4. Right *TreeNode
    5. }
    6. func findSecondMinimumValue(root *TreeNode) int {
    7. return dfs(root, root.Val)
    8. }
    9. func dfs(root *TreeNode, s int) int {
    10. // If root is nil, that means we can't find anything,
    11. // we return -1
    12. if root == nil {
    13. return -1
    14. }
    15. // If the current tree value is bigger than the smallest
    16. // element we hat, that means we have found the second smallest
    17. // one in the tree, since all subtrees is greater or equal to this
    18. // value.
    19. if root.Val > s {
    20. return root.Val
    21. }
    22. sLeft := dfs(root.Left, s)
    23. sRight := dfs(root.Right, s)
    24. if sLeft == -1 {
    25. return sRight
    26. }
    27. if sRight == -1 {
    28. return sLeft
    29. }
    30. return min(sLeft, sRight)
    31. }
    32. func min(a, b int) int {
    33. if a < b {
    34. return a
    35. }
    36. return b
    37. }