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
给定一个二叉树,对其求树中两个元素的和是否满足给定值。
1. 对二叉树进行中序遍历并把结果放入一个数组中
2. 对数组进行Two Pointer查找即可。
/** * 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> inOrder; bool findTarget(TreeNode* root, int k) { if (root == nullptr) return false; inOrdertoVec(root); if (inOrder.size() == 1) return false; int left = 0, right = inOrder.size() - 1; while (left < right) { int sum = inOrder[left] + inOrder[right]; if (sum == k) return true; else if (sum < k) left++; else right--; } return false; } vector<int> inOrdertoVec(TreeNode* root) { if (root == nullptr) return inOrder; stack<TreeNode*> s; while (root || !s.empty()) { if (root != nullptr) { s.push(root); root = root->left; } else { root = s.top(); inOrder.push_back(root->val); s.pop(); root = root->right; } } return inOrder; } }; // 35 ms
时间: 2024-10-08 13:05:51