Skip to content

Commit b9672d2

Browse files
authored
Create 1123. Lowest Common Ancestor of Deepest Leaves (#760)
2 parents fc4c43b + aa225e8 commit b9672d2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: 1123. Lowest Common Ancestor of Deepest Leaves

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
13+
class Solution {
14+
public:
15+
TreeNode* helper(unordered_set<TreeNode*>&s, TreeNode *root){
16+
if(!root) return NULL;
17+
if(s.count(root))return root;
18+
TreeNode* l = helper(s, root->left);
19+
TreeNode* r = helper(s, root->right);
20+
if(l && r)return root;
21+
return l ? l : r;
22+
}
23+
TreeNode* lcaDeepestLeaves(TreeNode* root) {
24+
unordered_set<TreeNode*>s;
25+
queue<TreeNode*>q;
26+
q.push(root);
27+
while(q.size()){
28+
int n = q.size();
29+
s.clear();
30+
while(n--){
31+
TreeNode* temp = q.front();
32+
q.pop();
33+
s.insert(temp);
34+
if(temp->left) q.push(temp->left);
35+
if(temp->right) q.push(temp->right);
36+
}
37+
}
38+
return helper(s, root);
39+
}
40+
};

0 commit comments

Comments
 (0)