653. 兩數之和 IV - 輸入 BST(樹)(BST)(有序數組的兩數之和)

在這裏插入圖片描述
方法一:
將BST的值存儲到HashMap中,轉化爲 兩數和爲目標值的問題;LeetCode 1 兩數之和

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private HashMap<Integer,Integer> map = new HashMap<>(); 
    public void BSTtoHashMap(TreeNode root){
        if(root == null) return;
        BSTtoHashMap(root.left);
        map.put(root.val,1);
        BSTtoHashMap(root.right);
    }
    public boolean findTarget(TreeNode root, int k) {
        BSTtoHashMap(root);
        return find(root,k);
    }

    public boolean find(TreeNode root,int k){
        if(root == null) return false;

        int subElem = k-root.val;
        //subElem!=root.val,考慮 測試用例 [1] 2,即map中匹配的不能是元素自己
        if(map.containsKey(subElem)&&subElem!=root.val){
            return true;
        }
        boolean left = findTarget(root.left,k);
        boolean right = findTarget(root.right,k);

        return (left||right);
    }
}

因爲BST每個元素的值唯一,
也可以存儲到HashSet中
這裏把構建HashSet和遍歷合到一步,提高了效率

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set < Integer > set = new HashSet();
        return find(root, k, set);
    }
    public boolean find(TreeNode root, int k, Set < Integer > set) {
        if (root == null)
            return false;
        if (set.contains(k - root.val))
            return true;
        set.add(root.val);
        return find(root.left, k, set) || find(root.right, k, set);
    }
}

方法二:
BFS+HashSet

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Set < Integer > set = new HashSet();
        Queue < TreeNode > queue = new LinkedList();
        queue.add(root);
        while (!queue.isEmpty()) {
            if (queue.peek() != null) {
                TreeNode node = queue.remove();
                if (set.contains(k - node.val))
                    return true;
                set.add(node.val);
                queue.add(node.right);
                queue.add(node.left);
            } else
                queue.remove();
        }
        return false;
    }
}

方法三:
利用BST的中序遍歷是有序的,將本問題轉化成LeetCode 167.兩數之和
兩數之和II的思路
在這裏插入圖片描述

public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        List < Integer > list = new ArrayList();
        inorder(root, list);
        int l = 0, r = list.size() - 1;
        while (l < r) {
            int sum = list.get(l) + list.get(r);
            if (sum == k)
                return true;
            if (sum < k)
                l++;
            else
                r--;
        }
        return false;
    }
    public void inorder(TreeNode root, List < Integer > list) {
        if (root == null)
            return;
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章