Two Sum BSTs
给两个bst, 然后看是不是能做two sum.
先用inorder变成array, 然后做two sum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { vector<int> v; inorder(root1, v); return twosum(v, root2, target); } void inorder(TreeNode* root, vector<int>& v){ if(!root) return; inorder(root->left, v); v.push_back(root->val); inorder(root->right, v); } bool twosum(vector<int>& v, TreeNode* root, int t) { if(!root) return false; return binary_search(v.begin(), v.end(), t - root->val) || twosum(v, root->left, t) || twosum(v, root->right, t);; } }; |