首页 > 其他分享 >leetcode-671. 二叉树中第二小的节点

leetcode-671. 二叉树中第二小的节点

时间:2023-01-08 21:01:06浏览次数:63  
标签:right return 671 dfs 二叉树 TreeNode root leetcode left

dfs 取左右子树第二大的值进行比较

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findSecondMinimumValue(root *TreeNode) int {
    val := dfs(root, root.Val)

    return val
}

func dfs(root *TreeNode, minV int) int {
    if root == nil {
        return -1
    }

    if root.Val > minV {
        return root.Val
    }

    left := dfs(root.Left, minV)
    right := dfs(root.Right, minV)

    if left == -1 {
        return right
    } else if right == -1 {
        return left
    } else if left < right {
        return left
    } else {
        return right
    }

}

参考

671. 二叉树中第二小的节点 - 力扣(Leetcode)

标签:right,return,671,dfs,二叉树,TreeNode,root,leetcode,left
From: https://www.cnblogs.com/wudanyang/p/17035325.html

相关文章

  • leetcode-2185. 统计包含给定前缀的字符串
    简单题,重拳出击funcprefixCount(words[]string,prefstring)int{validCnt:=0for_,w:=rangewords{notValid:=falseiflen(w)......
  • leetcode-409-easy
    LongestPalindromeGivenastringswhichconsistsoflowercaseoruppercaseletters,returnthelengthofthelongestpalindromethatcanbebuiltwiththose......
  • leetcode-345-easy
    ReverseVowelsofaStringGivenastrings,reverseonlyallthevowelsinthestringandreturnit.Thevowelsare'a','e','i','o',and'u',andtheycan......
  • leetcode-643-easy
    MaximumAverageSubarrayIYouaregivenanintegerarraynumsconsistingofnelements,andanintegerk.Findacontiguoussubarraywhoselengthisequalto......
  • leetcode-496-easy
    NextGreaterElementIThenextgreaterelementofsomeelementxinanarrayisthefirstgreaterelementthatistotherightofxinthesamearray.Youar......
  • leetcode-521-easy
    LongestUncommonSubsequenceIGiventwostringsaandb,returnthelengthofthelongestuncommonsubsequencebetweenaandb.Ifthelongestuncommonsubseq......
  • leetcode-551-easy
    StudentAttendanceRecordIYouaregivenastringsrepresentinganattendancerecordforastudentwhereeachcharactersignifieswhetherthestudentwasab......
  • leetcode-485-easy
    MaxConsecutiveOnesGivenabinaryarraynums,returnthemaximumnumberofconsecutive1'sinthearray.Example1:Input:nums=[1,1,0,1,1,1]Output:3E......
  • leetcode-434-easy
    NumberofSegmentsinaStringGivenastrings,returnthenumberofsegmentsinthestring.Asegmentisdefinedtobeacontiguoussequenceofnon-spacech......
  • 【LeetCode数组#4】长度最小的子数组
    长度最小的子数组力扣题目链接(opensnewwindow)给定一个含有n个正整数的数组和一个正整数s,找出该数组中满足其和≥s的长度最小的连续子数组,并返回其长度。如......