[InterviewBit] Consecutive Parent - Child

Consecutive Parent - Child

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* A, long long par, int& res) {
if(!A) return;
res += abs(par - A->val) == 1;
dfs(A->left, A->val, res);
dfs(A->right, A->val, res);
}
int Solution::consecutiveNodes(TreeNode* A) {
if(!A) return 0;
int res = 0;
dfs(A,A->val + 2ll,res);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/17/PS/interviewbit/consecutive-parent-child/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.