【LeetCode】653. Two Sum IV
来源:互联网 发布:java 字符串补位 编辑:程序博客网 时间:2024/05/16 12:00
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 7Target = 9Output: True
Example 2:
Input: 5 / \ 3 6 / \ \2 4 7Target = 28Output: False
题意是在一个二叉排序树寻找是否有两个数之和等于K。
方法1:直接递归查找。
class Solution {public: map<int,bool> mp; bool findTarget(TreeNode* root, int k) { if(root==NULL) return false; if(mp[k-root->val])return true; else{ mp[root->val]=true; return findTarget(root->left,k)||findTarget(root->right,k); } }};
方法2:先通过DFS遍历二叉树,把数字存放在一个VECTOR里面,然后再查找。
class Solution {public: map<int,bool> mp; vector<int> vec; void DFS(TreeNode* root){ if(root==NULL)return; DFS(root->left); vec.push_back(root->val); DFS(root->right); } bool findTarget(TreeNode* root, int k) { DFS(root); for(int i=0;i<vec.size();i++){ if(mp[k-vec[i]]){ return true; } mp[vec[i]]=true; } return false; }};
阅读全文
0 0
- leetcode 653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- Leetcode 653. Two Sum IV
- 【LeetCode】653. Two Sum IV
- leetcode 653. Two Sum IV
- leetcode 653. Two Sum IV
- [LeetCode]653. Two Sum IV
- leetcode: 653. Two Sum IV
- leetcode 653. Two Sum IV
- LeetCode 653. Two Sum IV
- LeetCode-653. Two Sum IV
- leetcode 653. Two Sum IV
- leetcode 653. Two Sum IV
- leetcode[Two Sum IV
- LeetCode Two Sum IV
- leetcode Two Sum IV
- [Leetcode] Binary tree--653. Two Sum IV
- freeswitch系列三 SIP软电话xlite、linphonec接入kamailio+freeswitch
- xcodeDefault.xctoolchain/user/bin/swiftcfailed with exit code 1
- 基于FPGA的RGB565_YCbCr_Gray算法实现
- HDU 6170:Two strings
- CSS 所有属性
- 【LeetCode】653. Two Sum IV
- javaweb项目出现中文乱码问题的解决方案。
- maven项目使用本地jar部署后找不到jar
- POJ 2018 Best Cow Fences + UVA Live 4726 Average 斜率优化DP
- Vim编辑器的简单使用
- Java开发中的23钟设计模式
- 正则表达式各个符号的含义概述
- 移动H5前端性能优化指南
- setAttribute和setParameter方法的区别