[LeetCode By Go 24]653. Two Sum IV - Input is a BST

题目

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:
Input:

    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True
Example 2:
Input:

    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

解题思路

先中序遍历所有节点,放进slice中,然后两端查找寻找是否有解

代码

twoSumBST.go

package _653_Two_Sum_IV_Input_BST

import "fmt"

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

//middle search
func MiddleSearch(root *TreeNode, valSlice *[]int) {
    if nil == root {
        return
    }
    MiddleSearch(root.Left, valSlice)
    (*valSlice) = append(*valSlice, root.Val)
    MiddleSearch(root.Right, valSlice)
}
func FindTarget(root *TreeNode, k int) bool {
    if nil == root {
        return false
    }

    var valSlice []int
    MiddleSearch(root, &valSlice)

    fmt.Printf("val:%+v", valSlice)
    for i, j := 0, len(valSlice) - 1; i < j; {
        if k == valSlice[i] + valSlice[j] {
            return true
        } else if k < valSlice[i] + valSlice[j] {
            j--
        } else if k > valSlice[i] + valSlice[j] {
            i++
        }

    }

    return false
}

测试

twoSumBST_test.go

package _653_Two_Sum_IV_Input_BST

import "testing"

func InitNode(val int, left *TreeNode, right *TreeNode) (ret *TreeNode){
    ret = new(TreeNode)
    ret.Val = val
    ret.Left = left
    ret.Right = right

    return ret
}

func TestFindTarget(t *testing.T) {
    l3_1 := InitNode(2, nil, nil)
    l3_2 := InitNode(4, nil, nil)
    l3_3 := InitNode(7, nil, nil)

    l2_1 := InitNode(3, l3_1, l3_2)
    l2_2 := InitNode(6, nil, l3_3)
    root := InitNode(5, l2_1, l2_2)

    want := true

    ret := FindTarget(root, 9)

    if ret == want {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want, ret)
    }

    r2_1 := InitNode(1, nil, nil)
    r2_2 := InitNode(3, nil, nil)

    input2 := InitNode(2, r2_1, r2_2)

    want2 := true
    ret2 := FindTarget(input2, 3)

    if ret2 == want2 {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want2, ret2)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,348评论 0 33
  • 昨天想把这两天写的一篇打卡文丰富下,完善后做成一篇公众号微信,就动手添加了一部分内容,从300余字也变成了500余...
    皮皮老猫阅读 1,872评论 2 4
  • 同一件事情,我与十人说我都能忍住眼泪。 但与你说,刚一开口我已泪如雨下。
    一只没有翅膀的鸟阅读 2,372评论 0 0
  • 记得第一次教研时,我紧张的不知如何是好,你问我最坏的结果是什么?我说还没签合同,大概就是不要我了。那我正好去找你。...
    凌000阅读 1,248评论 0 0