leetcode 653. Two Sum IV
来源:互联网 发布:php邮箱正则表达式 编辑:程序博客网 时间:2024/05/17 07:47
写在前面
这几天做到的题目都属于普通解法很容易想到,但有更好优化结果的类型,本题大概也可归于此类。
题目描述
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
思路分析
直观解释本题就是从BST树中找出两个元素,和为某个给定的值。一个直接的思路是利用BST树的性质做中序遍历,得到一个排序数组,同时从数组左侧和右侧末尾开始遍历求和,更新下标,找到满足条件的元素。这种解法从时间复杂度角度来看无疑是满足要求的,但如果题目要求不能使用额外存储,明显就不满足要求了。
从递归的角度去考虑这个问题,简单的中序 先序 后序遍历不可能得到AC解,因为这些遍历方式不能遍历所有的可能(基本只能是根节点和当前子树的关系,不同子树的关系无法判断),也就是说,针对每个结点都需要遍历所有的可能,DFS满足这种情况,对于每一个结点,都需要从根结点开始DFS所有的可能(BST的性质在DFS的过程中利用),由此可以写出以下代码:
/** * 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 findTarget(TreeNode* root, int k) { if(root == nullptr) return false; return dfs(root,root,k); } bool dfs(TreeNode* root,TreeNode* curr,int k) { if(curr== nullptr) return false; bool fin = find(root,curr,k-curr->val); if(fin) return true; return dfs(root,curr->left,k)||dfs(root,curr->right,k); } bool find(TreeNode* root,TreeNode* curr,int value) { if(root == nullptr) return false; if(root->val == value&& root!=curr) return true; bool left = false; if(root->val>value) left = find(root->left,curr,value); if(left) return true; return find(root->right,curr,value); }};
阅读全文
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
- *TEST 6 for NOIP + NOIP初赛
- 了解PHP中Stream(流)的概念与用法
- Android ADB 端口占用问题解决方案
- 【笔记】《WebGL编程指南》学习-第7章进入三维世界(3-可视空间)
- InetAddress与URL类
- leetcode 653. Two Sum IV
- 移动硬盘突然在电脑上无法显示
- Spring-Boot构建博客系统
- 数论概论 定理总结
- python批量修改图片后缀名
- G
- usaco 1.2 Milking Cows
- Android异步消息机制-深入理解Handler、Looper和MessageQueue之间的关系
- HashMap的工作原理