- Leetcode PHP题解--D89 653. Two Sum
- 653. Two Sum IV - Input is a BST
- 【2错-2】Two Sum IV - Input is a BS
- 653. Two Sum IV - Input is a BST
- 653. Two Sum IV - Input is a BST
- 653. Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- Leetcode 653. Two Sum IV - Input
- 算法题,Two Sum IV - Input is a BST
- [刷题防痴呆] 0653 - 两数之和IV - 输入BST (T
这周contest的签到题。我感觉应该有别的做法吧,但我直接把它遍历出来按照标准TWO SUM做的。。
而且在遍历的时候我竟然以为bst遍历要用preorder了。。。。MDZZ
public boolean findTarget(TreeNode root, int k) {
List<Integer> 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<Integer> list) {
if (root == null) {
return;
}
preOrder(root.left, list);
list.add(root.val);
preOrder(root.right, list);
}
网友评论