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);
}
}
相關文章
- A+B for Input-Output Practice (IV) (sdut oj)
- LeetCode-Combination Sum IVLeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- (BST)升序陣列變為BST樹陣列
- Java加密之IVJava加密
- 450-Delete Node in a BSTdelete
- 樹-BST基本實現
- IV. Mip-NeRF
- Leetcode-Recover BSTLeetCode
- IV.2 解析數論
- Delphi物件模型(Part IV) (轉)物件模型
- LeetCode-Inorder Successor in BSTLeetCode
- LeetCode-Largest BST SubtreeLeetCode
- Leetcode-Validate BSTLeetCode
- GCD SUMGC
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- SAP HUM 巢狀HU初探 IV巢狀
- IV.4 代數幾何
- IV.3 計算數論
- $(":input")和$("input")區別
- [LeetCode] 776. Split BSTLeetCode
- 從BST到LSM的進階之路
- Leetcode Kth Smallest Element in a BSTLeetCode
- 二叉堆、BST 與平衡樹
- leetcode15&16_3Sum&4SumLeetCode
- 破解冰盾IV (2千字)
- delete input 與 delete all inputdelete
- php des加密用java解析不了 改個模式 加個IV php金鑰/IV要求都是8位PHP加密Java模式
- input
- 二叉排序樹BST及CRUD操作排序
- Leetcode-Convert Sorted Array to BSTLeetCode
- Python -- raw_input() and input() -- ACMPythonACM
- 買賣股票的最佳時機 IV javaJava
- oracle Administrator's guide part IVOracleGUIIDE
- SQL groupby sum 用法SQL
- Split Array Largest Sum
- Pairwise Sum and DivideAIIDE
- oracle 字串 聚合 sumOracle字串