LeetCode - Easy - 653. Two Sum IV - Input is a BST

Topic

  • Tree

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:

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

Example 2:

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:

  • The number of nodes in the tree is in the range [ 1 , 1 0 4 ] [1, 10^4] [1,104].
  • − 1 0 4 < = N o d e . v a l < = 1 0 4 -10^4 <= Node.val <= 10^4 104<=Node.val<=104
  • root is guaranteed to be a valid binary search tree.
  • − 1 0 5 < = k < = 1 0 5 -10^5 <= k <= 10^5 105<=k<=105

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));
	}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值