LeetCode-Two Sum IV
阿新 • • 發佈:2018-12-18
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
題意:計算在一顆二叉搜尋樹中能否找到兩個節點,使得這兩個節點的節點值之和與指定的元素相同;
解法:要在一個序列中找到兩個數num1,num2之和為指定的元素target,換個角度想,就是計算能否找到target-num2這個元素;因此,我們可以遍歷二叉樹(前序,中序,後序或者層次遍歷都可以)將所有節點值儲存在表中;之後,對錶中每個節點值num,判斷在表中是否存在另外一個元素target-num(並且這個元素和num不是同一個元素);
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { Set<Integer> nodes = new HashSet<>(); public boolean findTarget(TreeNode root, int k) { storeTreeNode(root); Iterator<Integer> it = nodes.iterator(); while (it.hasNext()) { int first = it.next(); if (nodes.contains(k - first) && first != (k - first)) { return true; } } return false; } private void storeTreeNode(TreeNode root) { if (root == null) return; nodes.add(root.val); storeTreeNode(root.left); storeTreeNode(root.right); } }