[LeetCode] 653. Two Sum IV - Input is a BST

本文介绍了LeetCode上二数之和IV:输入为BST问题的三种解题方法:递归(DFS)、BFS及二叉树遍历。通过实例详细解析了每种方法的实现过程及优缺点,最后总结了适用于不同场景的最佳实践。

原题链接: https://leetcode.com/problems/two-sum-iv-input-is-a-bst/

题目描述

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.

在这里插入图片描述
在这里插入图片描述

解题思路

LeetCode给出了三种方法,分别是递归(DFS)、BFS和二叉树。
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/solution/

1. 递归

按照DFS的顺序,先找到一个a,然后判断HashSet中是否有等于k-a的b,如果有k-a的话,就到了,否则把a放入这个集合。这里用递归做,优点是代码简单,缺点是Runtime和Memory都比较大。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    	Set<Integer> con= new HashSet();
	
		public boolean findTarget(TreeNode root, int k) {
		if(root == null) {
			return false;
		}
		if(con.contains(k-root.val)) {
			return true;
		}
		else {
			con.add(root.val);
		}	
		return findTarget(root.left,k) || findTarget(root.right,k);
    }
}

2. BFS

就是按照BFS的方式,扫描一遍树。

public class Solution {
	List<Integer> con = new ArrayList();
	Queue < TreeNode > qu = new LinkedList();
	public boolean findTarget(TreeNode root, int k) {
        
        qu.add(root);
		while(qu.isEmpty()!= true) {
			TreeNode a = qu.remove();
			
			if(con.contains(k-a.val)) {
				return true;
			}
			else {
				con.add(a.val);
			}
			
			if(a.left != null) {
				qu.add(a.left);
			}
			if(a.right!=null) {
				qu.add(a.right);
			}
		}
		return false;
    }
}

queue的一些操作

add 增加一个元索 ,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素, 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素, 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞

3. 二叉树

二叉树有三种遍历方式:前序、中序、后序遍历。采用中序遍历,会将二叉树变为一个递增的数组。然后再使用二分,在这个递增的数组上用双指针l和r从两头逼近就可以了。

class Solution {
  
	List<Integer> con = new ArrayList();
	public boolean findTarget(TreeNode root, int k) {
        
		inorder(root,con);
		int l = 0;
		int r = con.size()-1;
		while(l < r) {
			int sum = con.get(l) + con.get(r);
			if(sum == k) {return true;}
			else if(sum > k) {r--;}
			else {l++;}
		}
		return false;
    }
	
	public void inorder(TreeNode root,List<Integer> con) {
		if(root == null) {
			return;
		}
		inorder(root.left,con);
		con.add(root.val);
		inorder(root.right,con);
	}
}

参考资料

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/solution/
https://www.cnblogs.com/lemon-flm/p/7877898.html

n-Sum专题相关题目

1. Two Sum
15. 3Sum
16. 3Sum Closest
18. 4Sum
167. Two Sum II - Input array is sorted
560. Subarray Sum Equals K
653. Two Sum IV - Input is a BST

根据原作 https://pan.quark.cn/s/459657bcfd45 的源码改编 Classic-ML-Methods-Algo 引言 建立这个项目,是为了梳理和总结传统机器学习(Machine Learning)方法(methods)或者算法(algo),和各位同仁相互学习交流. 现在的深度学习本质上来自于传统的神经网络模型,很大程度上是传统机器学习的延续,同时也在不少时候需要结合传统方法来实现. 任何机器学习方法基本的流程结构都是通用的;使用的评价方法也基本通用;使用的一些数学知识也是通用的. 本文在梳理传统机器学习方法算法的同时也会顺便补充这些流程,数学上的知识以供参考. 机器学习 机器学习是人工智能(Artificial Intelligence)的一个分支,也是实现人工智能最重要的手段.区别于传统的基于规则(rule-based)的算法,机器学习可以从数据中获取知识,从而实现规定的任务[Ian Goodfellow and Yoshua Bengio and Aaron Courville的Deep Learning].这些知识可以分为四种: 总结(summarization) 预测(prediction) 估计(estimation) 假想验证(hypothesis testing) 机器学习主要关心的是预测[Varian在Big Data : New Tricks for Econometrics],预测的可以是连续性的输出变量,分类,聚类或者物品之间的有趣关联. 机器学习分类 根据数据配置(setting,是否有标签,可以是连续的也可以是离散的)和任务目标,我们可以将机器学习方法分为四种: 无监督(unsupervised) 训练数据没有给定...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值