[InterviewBit] Burn a Tree

Burn a 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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int dfs1(TreeNode* node, unordered_map<int,int>& mp) {
if(!node) return 0;
int& now = mp[node->val];
now = max(now, dfs1(node->left, mp));
now = max(now, dfs1(node->right, mp));
return now + 1;
}
void dfs2(TreeNode* node, int t, int& res, int o, unordered_map<int,int>& mp) {
if(!node) return;
if(node->val == t) res = max(mp[node->val], o);
if(node->left) {
dfs2(node->left, t, res, max(o + 1, node->right ? mp[node->right->val] + 1 : 0), mp);
}
if(node->right) {
dfs2(node->right, t, res, max(o + 1, node->left ? mp[node->left->val] + 1 : 0), mp);
}
}
int Solution::solve(TreeNode* A, int B) {
int res = 0;
unordered_map<int, int> mp;
dfs1(A,mp);
dfs2(A,B,res,0,mp);
return res + 1;
}

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