File tree 1 file changed +90
-0
lines changed
1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for binary tree
3
+ * struct TreeNode {
4
+ * int val;
5
+ * TreeNode *left;
6
+ * TreeNode *right;
7
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
+ * };
9
+ */
10
+ void inorder (TreeNode* A, unordered_map<int , vector<int >> &mp){
11
+
12
+ if (!A) return ;
13
+
14
+ inorder (A->left , mp);
15
+
16
+ if (A->left ){
17
+
18
+ mp[A->val ].push_back (A->left ->val );
19
+
20
+ mp[A->left ->val ].push_back (A->val );
21
+
22
+ }
23
+
24
+ if (A->right ){
25
+
26
+ mp[A->val ].push_back (A->right ->val );
27
+
28
+ mp[A->right ->val ].push_back (A->val );
29
+
30
+ }
31
+
32
+ inorder (A->right , mp);
33
+
34
+ }
35
+
36
+
37
+ int Solution::solve (TreeNode* A, int B) {
38
+
39
+ unordered_map<int , vector<int > > mp;
40
+
41
+ inorder (A, mp);
42
+
43
+ unordered_map<int , int > isVisited;
44
+
45
+ queue<int > q;
46
+
47
+ q.push (B);
48
+
49
+ isVisited[B]=1 ;
50
+
51
+ int sec=-1 ;
52
+
53
+ while (!q.empty ()){
54
+
55
+ vector<int > v;
56
+
57
+ while (!q.empty ()){
58
+
59
+ isVisited[q.front ()]=1 ;
60
+
61
+ for (auto n: mp[q.front ()]){
62
+
63
+ if (!isVisited[n]){
64
+
65
+ v.push_back (n);
66
+
67
+ }
68
+
69
+ }
70
+
71
+ q.pop ();
72
+
73
+ }
74
+
75
+ if (v.size ()>0 ){
76
+
77
+ for (auto num: v) q.push (num);
78
+
79
+ }
80
+
81
+ sec++;
82
+
83
+ }
84
+
85
+ return sec;
86
+
87
+ }
88
+
89
+
90
+
You can’t perform that action at this time.
0 commit comments