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
|
int search(TreeNode* node, int n, int l, int r) { if(!node) return 0; if(node->val == n) return 1; if(l <= n and n <= r) { return search(node->left, n, l, node->val - 1) or search(node->right, n, node->val + 1, r); } return 0; } int dfs(TreeNode* node, int sum, TreeNode* root) { if(!node) return 0; int n = sum - node->val; if(n != node->val and search(root, n, INT_MIN, INT_MAX)) return 1; return dfs(node->left, sum, root) or dfs(node->right, sum, root); } int Solution::t2Sum(TreeNode* A, int B) { return dfs(A,B,A); }
|