-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLCA_of_Deepest_Leaves.cpp
More file actions
40 lines (36 loc) · 1008 Bytes
/
LCA_of_Deepest_Leaves.cpp
File metadata and controls
40 lines (36 loc) · 1008 Bytes
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
// https://leetcode.com/contest/weekly-contest-145/problems/lowest-common-ancestor-of-deepest-leaves/
// Problem : Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* dfs(TreeNode* A, int h, int height) {
if(!A)
return A;
if(h == height)
return A;
TreeNode* l = dfs(A -> left, h + 1, height);
TreeNode* r = dfs(A -> right, h + 1, height);
if(l && r)
return A;
if(l)
return l;
return r;
}
int findH(TreeNode* root) {
if(!root)
return -1;
return 1 + max(findH(root -> left), findH(root -> right));
}
TreeNode* lcaDeepestLeaves(TreeNode* root) {
int height = findH(root);
return dfs(root, 0, height);
}
};