标签:ndt 遍历 ash set 关系 elements roo root NPU
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
//Time: O(n), Space: O(n) //开始以为BST用二分,后来发现这道题和二叉搜索树没啥关系,就是遍历一颗普通的二叉树 public boolean findTarget(TreeNode root, int k) { if (root == null) { return false; } HashSet<Integer> set = new HashSet<Integer>(); return dfs(root, k, set); } private boolean dfs(TreeNode root, int k, HashSet<Integer> set) { if (root == null) { return false; } if (set.contains(k - root.val)) { return true; } set.add(root.val); return dfs(root.left, k, set) || dfs(root.right, k, set); }
653. Two Sum IV - Input is a BST
标签:ndt 遍历 ash set 关系 elements roo root NPU
原文地址:https://www.cnblogs.com/jessie2009/p/9771737.html