LeetCode Easy653中两数之和输入为BST的示例分析

发布时间:2021-09-17 15:59:37 作者:柒染
来源:亿速云 阅读:105

LeetCode Easy653中两数之和输入为BST的示例分析,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Description

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1: LeetCode Easy653中两数之和输入为BST的示例分析

Input: root = [5,3,6,2,4,null,7], k = 9
Output: true

Example 2:

LeetCode Easy653中两数之和输入为BST的示例分析

Input: root = [5,3,6,2,4,null,7], k = 28
Output: false

Example 3:

Input: root = [2,1,3], k = 4
Output: true

Example 4:

Input: root = [2,1,3], k = 1
Output: false

Example 5:

Input: root = [2,1,3], k = 3 Output: true

Constraints:

Analysis

用两指针方法,一指针前序遍历,另一指针二分查找。

Submission

public class TwoSumIVInputIsABST {

	public boolean findTarget(TreeNode root, int k) {
		return traverse(root, root, k);
	}

	// 前序遍历
	private boolean traverse(TreeNode node, TreeNode root, int k) {
		if (node == null)
			return false;

		// node.val恰好是k的一半时,根据BST特性,没必要找另一个节点
		if (2 * node.val != k && findTarget2(root, k - node.val))
			return true;

		return traverse(node.left, root, k) || traverse(node.right, root, k);
	}

	// 二分查找
	private boolean findTarget2(TreeNode node, int targetValue) {
		if (node == null)
			return false;

		if (node.val == targetValue)
			return true;

		return findTarget2(targetValue < node.val ? node.left : node.right, targetValue);
	}

}

Test

import static org.junit.Assert.*;
import org.junit.Test;

import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;

public class TwoSumIVInputIsABSTTest {

	@Test
	public void test() {
		TwoSumIVInputIsABST obj = new TwoSumIVInputIsABST();

		TreeNode root1 = BinaryTree.integers2BinaryTree(5, 3, 6, 2, 4, null, 7);
		assertTrue(obj.findTarget(root1, 9));
		assertFalse(obj.findTarget(root1, 28));

		TreeNode root2 = BinaryTree.integers2BinaryTree(2, 1, 3);
		assertTrue(obj.findTarget(root2, 4));
		assertFalse(obj.findTarget(root2, 1));
		assertTrue(obj.findTarget(root2, 3));
	}
}

关于LeetCode Easy653中两数之和输入为BST的示例分析问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. LeetCode如何实现两数之和
  2. LeetCode中两数之和的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

leetcode bst

上一篇:Linux系统sudo命令详解

下一篇:Linux关机命令的用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》