653. Two Sum IV
来源:互联网 发布:服装图设计软件 编辑:程序博客网 时间:2024/05/22 02:24
题目
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分析
有些人用map保存所有元素并计数出现次数,然后利用k,在map中寻找k-val,也可以在每次找到一个节点时,对其进行从根节点开始的二叉搜索树遍历。
/** * 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: bool searchVal(TreeNode* root,TreeNode* Root,int k){//全局搜索k bool find=false; TreeNode* temp=Root; if(Root==NULL) return find; if(Root->val==k&&root!=Root){//如果有k值并且与之前的节点不一样,则返回true find=true; return find; } else if(k<Root->val){//否则去左右子树搜索 return searchVal(root,Root->left,k); } else return searchVal(root,Root->right,k); } bool findTarget(TreeNode* root, TreeNode* Root, int k) { bool find=false; if(root==NULL) return find; if(root->right!=NULL){//当右子树不为空时,搜索右子树里面有没有该值 find|=findTarget(root->right,Root,k); } if(root->left!=NULL){ find|=findTarget(root->left,Root,k); } find|=searchVal(root,Root,k-root->val);//全局搜索有没有k-root->val,其中root记录当前节点的指针,Root记录二叉搜索树的根节点指针 return find; } bool findTarget(TreeNode* root, int k){ return findTarget(root,root,k); }};
阅读全文
0 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
- JVET-A1001 JEM平台算法相关简介
- ccui.layout 横 竖方向布局,简单实现
- Nginx中的惊群现象解决方法
- QQ空间十亿级视频播放技术优化揭密
- java中的数据类型转换
- 653. Two Sum IV
- struct一些学习经验
- 设计模式——简单工厂
- HTTP与HTTPS的区别
- MVP简单实现
- [SMOJ2161]棋盘
- $.each遍历json对象
- 单链表的相关操作之创建
- c++引用