[InterviewBit] 2-Sum Binary Tree

2-Sum Binary Tree

  • Time : O(nlogn)
  • Space : O(1)
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/05/PS/interviewbit/2sum-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.