[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)
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/f258d1232bd8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞