LeetCode Easy653中兩數(shù)之和輸入為BST的示例分析,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
為源匯等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及源匯網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站設(shè)計、做網(wǎng)站、源匯網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
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, 10^4]$.
$-10^4 <= Node.val <= 10^4$
root
is guaranteed to be a validbinary search tree.
$-10^5 <= k <= 10^5$
用兩指針方法,一指針前序遍歷,另一指針二分查找。
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的一半時,根據(jù)BST特性,沒必要找另一個節(jié)點 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); } }
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)); } }
關(guān)于LeetCode Easy653中兩數(shù)之和輸入為BST的示例分析問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
當(dāng)前名稱:LeetCodeEasy653中兩數(shù)之和輸入為BST的示例分析
標(biāo)題網(wǎng)址:http://muchs.cn/article0/picpoo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站營銷、網(wǎng)站制作、建站公司、微信公眾號、、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)