leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
2017-12-19 21:50
477 查看
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
本题题意很简单,直接做一个中序遍历,存储到set中,然后做一次查询即可
这个是必须要注意的:注意set做查询的时候要把当前元素删除,然后查询之后再插入
代码如下:
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
本题题意很简单,直接做一个中序遍历,存储到set中,然后做一次查询即可
这个是必须要注意的:注意set做查询的时候要把当前元素删除,然后查询之后再插入
代码如下:
#include <iostream> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using namespace std; /* struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; */ class Solution { public: set<int> all; bool findTarget(TreeNode* root, int k) { dfs(root); for (auto i : all) { all.erase(i); if (all.find(k - i) != all.end()) return true; all.insert(i); } return false; } void dfs(TreeNode* root) { if (root == NULL) return; else { dfs(root->left); all.insert(root->val); dfs(root->right); } } };
相关文章推荐
- leetcode 530. Minimum Absolute Difference in 二叉搜索树的中序遍历 + 深度优先遍历DFS
- leetcode 669. Trim a Binary Search Tree 修建二叉搜索树BST + 深度优先遍历DFS
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- leetcode 450. Delete Node in a BST 二叉搜索树BST删除结点 + 深度优先遍历DFS
- leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历 + 很明显很经典的DP动态规划做法
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- leetcode 662. Maximum Width of Binary Tree 二叉树最大宽度 + 深度优先遍历DFS
- 【LeetCode】653. Two Sum IV - Input is a BST 解题报告
- leetcode 753. Cracking the Safe 深度优先遍历DFS
- leetcode 653. Two Sum IV - Input is a BST
- leetcode 222. Count Complete Tree Nodes 计算满二叉树的节点数量 + DFS深度优先遍历 + 公式计算
- LeetCode - 653. Two Sum IV - Input is a BST
- leetcode 473. Matchsticks to Square 火柴摆正方形 + 一个经典深度优先遍历DFS的应用
- leetcode 529. Minesweeper 扫雷游戏 + 经典的DFS深度优先遍历
- leetcode 617. Merge Two Binary Trees 二叉树合并 + 深度优先遍历DFS
- leetcode 650. 2 Keys Keyboard 最小复制粘贴次数 + 深度优先遍历DFS
- leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
- 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