-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLowestCommonAncestorOfDeepestLeaves.java
43 lines (35 loc) · 1.13 KB
/
LowestCommonAncestorOfDeepestLeaves.java
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
41
42
43
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
// https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
public class LowestCommonAncestorOfDeepestLeaves {
private final TreeNode input;
public LowestCommonAncestorOfDeepestLeaves(TreeNode input) {
this.input = input;
}
public TreeNode solution() {
int depth = depth(input);
return dfs(input, depth);
}
private int depth(TreeNode node) {
if (node != null) {
int left = depth(node.left);
int right = depth(node.right);
return 1 + Math.max(left, right);
}
return 0;
}
private TreeNode dfs(TreeNode node, int depth) {
if (node != null) {
if (depth == 1) {
return node;
}
TreeNode left = dfs(node.left, depth - 1);
TreeNode right = dfs(node.right, depth - 1);
if (left != null && right != null) {
return node;
}
return left != null ? left : right;
}
return null;
}
}