LeetCode-653. Two Sum IV - Input is a BST
2018-04-03 19:21
555 查看
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
Solution 1(C++)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0;}(); class Solution { set<int> s; bool dfs(TreeNode *cur, int k) { if (!cur) return false; if (s.count(k - cur->val)) return true; s.insert(cur->val); return dfs(cur->left, k) || dfs(cur->right, k); } public: bool findTarget(TreeNode* root, int k) { s.clear(); return dfs(root, k); } };
Solution 2(C++)
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { bool findVal(TreeNode* root, int val) { if(!root) return false; else if(root->val == val) return true; else if(root->val < val) return findVal(root->right, val); else return findVal(root->left, val); } bool findTargetHelper(TreeNode *root, TreeNode *current, int k) { if(!current||!root) return false; else if(current->val!=(k-current->val) && findVal(root, k-current->val)) return true; else if(findTargetHelper(root, current->left, k)) return true; else if(findTargetHelper(root, current->right, k)) return true; else return false; } public: bool findTarget(TreeNode* root, int k) { return findTargetHelper(root, root, k); } };
算法分析
解法一,我真的觉得有一种很重要的思想在其中,寻找两个数的和是否等于要求的数,其实可以转换成,对于一个数,判断其和与该数的差值是否在树中。这样问题就成功的转换了。所以解法一用了set,然后结合二叉树的遍历。比较简单直观的实现了问题的解决。虽然消耗了内存空间。解法二,使用了递归与分治。findTargetHelper函数实现分治,如果当前结点的值对应的加数没有找到,就在其左子节点与右子节点中分别寻找。findVal实现在二叉树中查找目标值。时间复杂度比1高。
程序分析
略。相关文章推荐
- [Leetcode] 653. Two Sum IV - Input is a BST 解题报告
- leetcode: 653. Two Sum IV - Input is a BST
- LeetCode653. Two Sum IV - Input is a BST
- <easy>LeetCode Problem -- 653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- Leetcode: 653. Two Sum IV - Input is a BST
- 2017.11.1 LeetCode - 653. Two Sum IV - Input is a BST
- leetcode653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST
- 【LeetCode】653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
- Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- LeetCode - 653. Two Sum IV - Input is a BST
- leetcode专题—653. Two Sum IV - Input is a BST
- LeetCode 653. Two Sum IV - Input is a BST
- LeetCode - 653. Two Sum IV - Input is a BST
- leetcode 653. Two Sum IV - Input is a BST
- LeetCode 653. Two Sum IV – Input is a BST
- Leetcode653. Two Sum IV - Input is a BST