LeetCode.653 Two Sum IV - Input is a BST
2018-01-25 16:14
435 查看
题目:
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:
Example 2:
分析:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
//给定规定二叉树,以及给定目标值,返回是否二叉树中是否存在两个节点的和等于目标值
//思路:利用set存储已经遍历的节点,递归查找
return backtrace(root,new HashSet<>(),k);
}
public boolean backtrace(TreeNode root,Set<Integer> set,int k){
if(root==null) return false;
if(set.contains(k-root.val)){
//说明存在剩余值
return true;
}
set.add(root.val);
return backtrace(root.left,set,k)||backtrace(root.right,set,k);
}
}
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 7 Target = 9 Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
分析:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
//给定规定二叉树,以及给定目标值,返回是否二叉树中是否存在两个节点的和等于目标值
//思路:利用set存储已经遍历的节点,递归查找
return backtrace(root,new HashSet<>(),k);
}
public boolean backtrace(TreeNode root,Set<Integer> set,int k){
if(root==null) return false;
if(set.contains(k-root.val)){
//说明存在剩余值
return true;
}
set.add(root.val);
return backtrace(root.left,set,k)||backtrace(root.right,set,k);
}
}
相关文章推荐
- Two Sum IV - Input is a BST
- leetcode Two Sum IV - Input is a BST 两个数的和
- LeetCode #653 Two Sum IV - Input is a BST
- LeetCode Two Sum IV - Input is a BST
- LeetCode 653: Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- LeetCode之Two Sum IV - Input is a BST(Kotlin)
- 算法分析与设计——LeetCode Problem.653 Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- leetcode[Two Sum IV - Input is a BST]//待整理多种解法
- Two Sum IV - Input is a BST(leetcode)
- [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
- leetcode 653 Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST问题及解法
- LeetCode Two Sum IV - Input is a BST
- Two Sum IV - Input is a BST
- LC-Two Sum IV - Input is a BST
- week19-leetcode #653-TwoSumIV-InputisaBST
- leetcode167: Two Sum II - Input array is sorted
- Array-Two Sum II - Input array is sorted