1214. 查找两棵二叉搜索树之和

    技术2023-07-12  68

    void inOrder(TreeNode *root, vector<int> &v) { if (!root) return; inOrder(root->left, v); v.emplace_back(root->val); inOrder(root->right, v); } bool twoSumBSTs(TreeNode *root1, TreeNode *root2, int target) { vector<int> v1, v2; inOrder(root1, v1); inOrder(root2, v2); int l = 0, r = v2.size() - 1; while (l < v1.size() && r >= 0) { int val = v1[l] + v2[r]; if (val > target) r--; else if (val < target) l++; else return true; } return false; }
    Processed: 0.008, SQL: 9