两数之和 IV - 输入二叉搜索树
给定一个二叉搜索树 root 和一个目标结果 k,如果二叉搜索树中存在两个元素且它们的和等于给定的目标结果,则返回 true。
示例 1:
输入: root = [5,3,6,2,4,null,7], k = 9
输出: true
示例 2:
输入: root = [5,3,6,2,4,null,7], k = 28
输出: false
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum-iv-input-is-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
屎山方式
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
//创建数字列表
ArrayList<Integer> list = new ArrayList<Integer>();
//递归遍历二叉树
preOrder(root,list);
for(int i=0;i<list.size()-1;i++){
for(int j=i+1;j<list.size();j++){
if(list.get(i)+list.get(j)==k)return true;
}
}
return false;
}
public void preOrder(TreeNode root,ArrayList list){
if(root != null){
list.add(root.val);
}else{
return;
}
preOrder(root.left,list);
preOrder(root.right,list);
}
}
Set遍历二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
//创建set集合,存储节点上的数据
HashSet<Integer> set = new HashSet<Integer>();
return preOrder(root,set,k);
}
//递归遍历树
public boolean preOrder(TreeNode node,HashSet set,int k){
//递归出口,遍历到空结点
if(node==null)return false;
//当满足条件时会把原有的false变为true
if(!set.contains(k- node.val)){
return true;
}
//添加set节点值
set.add(node.val);
//遍历左右根树
return preOrder(node.left,set,k) || preOrder(node.right,set,k);
}
}