首页 > 其他分享 >leetcode-653. 两数之和 IV - 输入二叉搜索树

leetcode-653. 两数之和 IV - 输入二叉搜索树

时间:2023-01-05 00:23:24浏览次数:60  
标签:二叉 TreeNode cur Val leetcode IV stack 两数

653. 两数之和 IV - 输入二叉搜索树 - 力扣(Leetcode)

用了迭代进行遍历二叉树,因为二叉搜索树的中序遍历是有序的,所以肯定左边大于右边,然后就可以用一个map来存放之前的数值,

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findTarget(root *TreeNode, k int) bool {
    if root == nil {
        return false
    }

    m := make(map[int]struct{})

    stack := []*TreeNode{}

    cur := root
    for cur != nil || len(stack) > 0 {
        for cur != nil {
            stack = append(stack, cur)
            cur = cur.Left
        }

        cur = stack[len(stack) - 1]
        stack = stack[:len(stack)-1]
        
        if _, ok := m[k-cur.Val]; ok {
            return true
        }

        m[cur.Val] = struct{}{}

        cur = cur.Right
    }

    return false
}

标签:二叉,TreeNode,cur,Val,leetcode,IV,stack,两数
From: https://www.cnblogs.com/wudanyang/p/17026395.html

相关文章

  • [LeetCode]015-三数之和
    >>>传送门题目给你一个整数数组nums,判断是否存在三元组[nums[i],nums[j],nums[k]]满足i!=j、i!=k且j!=k,同时还满足nums[i]+nums[j]+nums[k]==0......
  • ActiveMQ
    ActiveMQ初体验首先介绍下MQ,MQ英文名MessageQueue,中文名也就是大家用的消息队列,干嘛用的呢,说白了就是一个消息的接受和转发的容器,可用于消息推送。下面介绍主题,就是今天为大......
  • 重新编译keepalived-exporter源码,构建镜像
    1.githubhttps://github.com/mehdy/keepalived-exporter 2.dockerfileFROMgolang:1.17ENVGO111MODULE=on\GOPROXY="https://goproxy.cn,direct"COPYkeepa......
  • leetcode-387-easy
    FirstUniqueCharacterinaStringGivenastrings,findthefirstnon-repeatingcharacterinitandreturnitsindex.Ifitdoesnotexist,return-1.Examp......
  • leetcode-414-easy
    ThirdMaximumNumberGivenanintegerarraynums,returnthethirddistinctmaximumnumberinthisarray.Ifthethirdmaximumdoesnotexist,returnthemaxim......
  • leetcode-563-easy
    BinaryTreeTiltGiventherootofabinarytree,returnthesumofeverytreenode'stilt.Thetiltofatreenodeistheabsolutedifferencebetweenthesum......
  • leetcode-349-easy
    IntersectionofTwoArraysGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustbeuniqueandyoum......
  • leetcode-350-easy
    IntersectionofTwoArraysIIGiventwointegerarraysnums1andnums2,returnanarrayoftheirintersection.Eachelementintheresultmustappearasmany......
  • leetcode-367-easy
    ValidPerfectSquareGivenapositiveintegernum,returntrueifnumisaperfectsquareorfalseotherwise.Aperfectsquareisanintegerthatisthesquar......
  • 【Azure 应用服务】Azure Function Python函数部署到Azure后遇见 Value cannot be nul
    问题描述使用VSCode创建PythonFunction,处理EventHub中的数据。当部署到AzureFunctionApp后,函数无法执行,查看Function日志出现 Valuecannotbenull.(Parameter......