653-Two Sum IV - Input is a BST
Description
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.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
問題描述
給定二叉排序樹和一個目標數, 若二叉排序樹中存在兩個節點的值的和為目標數, 返回true, 否則, 返回false
問題分析
中序遍歷二叉排序樹獲取值的遞增序列, 然後通過兩個指標l和r來做
解法
public class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> list = new ArrayList();
inorder(root, list);
int l = 0, r = list.size() - 1;
while(l < r){
int sum = list.get(l) + list.get(r);
if(sum == k) return true;
if(sum < k) l++;
else r--;
}
return false;
}
public void inorder(TreeNode root, List < Integer > list) {
if(root == null) return;
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}
相關文章
- 力扣 653. 兩數之和 IV 二叉樹/binary-tree two-sum IV力扣二叉樹
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- SAP MM GR-based IV, 無GR不能IV?
- Java加密之IVJava加密
- [LeetCode] 776. Split BSTLeetCode
- 449-Serialize and Deserialize BST
- 450-Delete Node in a BSTdelete
- 樹-BST基本實現
- IV. Mip-NeRF
- 538-Convert BST to Greater Tree
- [LeetCode] 2326. Spiral Matrix IVLeetCode
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- GCD SUMGC
- Sum Problem
- 集合sum
- [LeetCode] 230. Kth Smallest Element in a BSTLeetCode
- LeetCode之Convert BST to Greater Tree(Kotlin)LeetCodeKotlin
- 15+18、3Sum 4Sum
- SAP HUM 巢狀HU初探 IV巢狀
- Python -- raw_input() and input() -- ACMPythonACM
- 從BST到LSM的進階之路
- 二叉堆、BST 與平衡樹
- input
- leetcode Sum系列LeetCode
- Sum of Left Leaves
- Path-sum
- Path Sum III
- Leetcode Path SumLeetCode
- B - Minimum Sum
- Range Minimum Sum
- Missing Subsequence Sum
- 初始化向量(IV)通俗解釋
- php des加密用java解析不了 改個模式 加個IV php金鑰/IV要求都是8位PHP加密Java模式
- 二叉排序樹BST及CRUD操作排序
- 買賣股票的最佳時機 IV javaJava
- 【Lintcode】393. Best Time to Buy and Sell Stock IV
- Leetcode 39 Combination SumLeetCode
- md5sum