/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
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);
}
}
每日一道Leetcode - 653. 两数之和 IV - 输入 BST【中序遍历】
猜你喜欢
转载自blog.csdn.net/weixin_41041275/article/details/112303836
今日推荐
周排行