LeetCode Two Sum IV

来源:互联网 发布:红外图谱数据库 编辑:程序博客网 时间:2024/05/21 17:31

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   7Target = 9Output: True

Example 2:

Input:     5   / \  3   6 / \   \2   4   7Target = 28Output: False

题解:此题要求在一棵二叉排序树中,寻找任意的两个节点的和等于给定的某个target值,如果存在这两个数的和为target,那么就输出true;否则就输出为false。此题我考虑先按照中序遍历,也就是左-根-右的顺序对一棵二叉树进行扫描,得到的是一串按照从小到大排列的数据,然后再根据从开始的节点和末尾的节点的和,再两两夹逼来寻找是否这两个数的和满足给定的这个target值。

public class findTarget{    public boolean findTarget(TreeNode root,int k)    {        ArrayList<Integer> list = new ArrayList<>();        inOrder(root,list);        for(int i = 0,j = list.size() - 1 ; i < j;)              //根据首尾进行相加来夹逼,得到和是否为target值。        {            if((list.get(i) + list.get(j)) == k)                return true;            else if(list.get(i) + list.get(j) < k)                i++;            else                j--;        }        return false;    }    public void inOrder(TreeNode root,ArrayList<Integer> list)   //递归方式来对一棵二叉树进行中序遍历    {        if(root == null)            return;        if(root.left != null)            inOrder(root.left,list);        list.add(root.val);        if(root.right != null)            inOrder(root.right,list);    }}



原创粉丝点击