1. 程式人生 > 實用技巧 >leetcode 653 兩數之和IV 輸入BST

leetcode 653 兩數之和IV 輸入BST

package com.example.lettcode.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Class FindTarget
 * @Description 653 兩數之和IV 輸入BST
 * 給定一個二叉搜尋樹和一個目標結果,
 * 如果 BST 中存在兩個元素且它們的和等於給定的目標結果,則返回 true。
 * <p>
 * 案例 1:
 * 輸入:
 * 5
 * / \
 * 3   6
 * / \   \
 * 2   4   7
 * Target = 9
 * 輸出: True
 * <p>
 * 案例 2:
 * 輸入:
 * 5
 * / \
 * 3   6
 * / \   \
 * 2   4   7
 * Target = 28
 * 輸出: False
 * @Author
 * @Date 2020/7/20
 **/
public class FindTarget {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
/**
 * 解法1: 先中序得到一個非遞減的序列,然後再判斷
 */
public static boolean findTarget(TreeNode root, int k) {
	boolean flag = false;
	List<Integer> integerList = new ArrayList<>();
	inOrder(root, integerList);
	int p = 0, q = integerList.size() - 1;
	while (p < q) {
		int tmp = integerList.get(p) + integerList.get(q);
		if (tmp == k) return true;
		if (tmp > k) q--;
		else if (tmp < k) p++;
	}
	return false;
}

public static void inOrder(TreeNode root, List<Integer> integerList) {
	if (root == null) return;
	inOrder(root.left, integerList);
	integerList.add(root.val);
	inOrder(root.right, integerList);
}
/**
 *  解法2:利用HashSet 儲存已經遍歷到的元素,判斷是否存在與當前元素之和為目標值的元素
 *  存在即返回false,否則加入到set中並遍歷左右子樹
 *  使用類靜態變數時每一個測試用例執行結束需要清除,否則會重複儲存之前的記錄
 *  或者使用類成員變數
 */
static Set<Integer> integerSet = new HashSet<>();

public static boolean findTarget(TreeNode root, int k) {
	if (root == null) return false;
	int tmp = k - root.val;
	if (integerSet.contains(tmp)) return true;
	integerSet.add(root.val);
	return findTarget(root.left, k) || findTarget(root.right, k);
}
// 測試用例
public static void main(String[] args) {
	TreeNode root = new TreeNode(5);
	TreeNode treeNode02 = new TreeNode(3);
	TreeNode treeNode03 = new TreeNode(6);
	root.left = treeNode02;
	root.right = treeNode03;
	TreeNode treeNode04 = new TreeNode(2);
	TreeNode treeNode05 = new TreeNode(4);
	treeNode02.left = treeNode04;
	treeNode02.right = treeNode05;
	TreeNode treeNode06 = new TreeNode(7);
	treeNode05.right = treeNode06;
	int target = 9;
	boolean ans = findTarget(root, target);
	integerSet.clear();
	System.out.println("FindTarget demo01 result:" + ans);

	target = 28;
	ans = findTarget(root, target);
	integerSet.clear();
	System.out.println("FindTarget demo02 result:" + ans);

	root = new TreeNode(1);
	target = 2;
	ans = findTarget(root, target);
	integerSet.clear();
	System.out.println("FindTarget demo03 result:" + ans);
}