[InterviewBit] Cousins in Binary Tree

Cousins in Binary Tree

  • Time :
  • Space :
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
32
33
34
35
36
37
38
39
40
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

void dfs1(TreeNode* A, int t, int p, int dep, int& level, int& par) {
if(!A) return;
if(A->val == t) {
par = p;
level = dep;
}
dfs1(A->left,t,A->val,dep + 1, level, par);
dfs1(A->right,t,A->val,dep + 1, level, par);
}

void dfs2(TreeNode* A, int p, int dep, int& level, int& par, vector<int>& res) {
if(!A) return;
if(dep > level) return;
if(dep == level) {
if(p != par) res.push_back(A->val);
return;
}
dfs2(A->left,A->val,dep + 1, level, par, res);
dfs2(A->right,A->val,dep + 1, level, par, res);
}

vector<int> Solution::solve(TreeNode* A, int B) {
if(!A) return {};
if(A->val == B) return {};
int level = -1, par = -1;
dfs1(A,B,-1,0,level,par);
vector<int> res;
dfs2(A,-1,0,level,par,res);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/27/PS/interviewbit/cousins-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.