LeetCode-653.Two Sum IV - Input is a BST
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
将二叉搜索树经中序遍历保存为递增数组,然后使用双指针
public boolean findTarget(TreeNode root, int k) { List<Integer> list = new ArrayList<Integer>(); midList(root,list); int left =0; int right =list.size()-1; while(left<right){ int sum =list.get(left)+list.get(right); if(sum==k){ return true; } else if(sum<k){ left++; } else{ right--; } } return false; } public void midList(TreeNode root,List<Integer > list){ if(root==null){ return; } midList(root.left,list); list.add(root.val); midList(root.right,list); }
浙公网安备 33010602011771号