-
思路一
- 这道题在数组中做过类似的~,所以自然就想到先中序遍历变成数组,然后用双指针做,这样的话需要两次遍历,如果在遍历的过程中搭配哈希表,那么遍历一次即可~
class Solution { public boolean findTarget(TreeNode root, int k) { Set<Integer> map = new HashSet<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode cur = root; while (null != cur || !stack.isEmpty()) { while (null != cur) { stack.push(cur); cur = cur.left; } cur = stack.pop(); if(map.contains(k-cur.val)) return true; map.add(cur.val); cur = cur.right; } return false; } }
-
思路二
- 我们之前用双指针做是因为left++ right–是很容易的操作,但是根据55题,这个类提供的迭代器可以从小到大遍历,如果我们修改内部遍历的方式,可以很简单的实现从大到小遍历~基于此想法,可以直接用双指针进行操作。在这种情况下,空间复杂度为O(h),主要是遍历时栈需要保存结点
- 我觉得还是思路一更好~ 所以这个就木有代码 O(∩_∩)O
09-27
2411
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-11
5179
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-27
1084
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-27
779
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)