653. Two Sum IV
来源:互联网 发布:机顶盒mac地址绑定 编辑:程序博客网 时间:2024/05/22 00:25
题目:
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思路:
本题,先利用先序遍历将结点值存储在数组里,再用find函数查找(k-当前结点)是否存在
代码:
/** * 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 {public:vector<int> res; bool findTarget(TreeNode* root, int k) { Preorder(root); for(int i=0;i<res.size();i++) { int temp =k - res[i]; if(find(res.begin(),res.end(),temp)!=res.begin()+i&&find(res.begin(),res.end(),temp)!=res.end()) return true; } return false; }private:void Preorder(TreeNode* root){ if(root!=NULL) { res.push_back(root->val); Preorder(root->left); Preorder(root->right); } }};
阅读全文
1 0
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 653. Two Sum IV
- 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
- MySql 5.7.13 for Mac 免安装版安装教程
- Linux中的ps命令
- 系统安装
- Android连续点击事件的实现
- Java IO流
- 653. Two Sum IV
- rqnoj514 字串距离
- 面试过程中手撕代码之二叉树
- 5-2 使用函数求奇数和
- JavaScript如何获得某一天的前一天日期
- 一、写在前面的话
- Eclipse、object
- 广度优先搜索总结
- ubuntu设置静态IP