653. Two Sum IV - Input is a BST

这周contest的签到题。我感觉应该有别的做法吧,但我直接把它遍历出来按照标准TWO SUM做的。。
而且在遍历的时候我竟然以为bst遍历要用preorder了。。。。MDZZ

    public boolean findTarget(TreeNode root, int k) {
        List list = new ArrayList<>();
        preOrder(root, list);
        int i = 0, j = list.size() - 1;
        while (i < j) {
            if (list.get(i) + list.get(j) == k) {
                return true;
            }
            if (list.get(i) + list.get(j) < k) {
                i++;
            } else {
                j--;
            }
        }
        return false;
    }

    private void preOrder(TreeNode root, List list) {
        if (root == null) {
            return;
        }
        preOrder(root.left, list);
        list.add(root.val);
        preOrder(root.right, list);
    }

你可能感兴趣的:(653. Two Sum IV - Input is a BST)