We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 15e1eb0 commit 5a896a6Copy full SHA for 5a896a6
solution/1123.Lowest Common Ancestor of Deepest Leaves/Solution.java
@@ -0,0 +1,27 @@
1
+class Solution {
2
+ public TreeNode lcaDeepestLeaves(TreeNode root) {
3
+ Data data = dfs(root);
4
+ return data.root;
5
+ }
6
+
7
+ private Data dfs(TreeNode root) {
8
+ if (root == null) {
9
+ return new Data(null, 0);
10
11
+ Data left = dfs(root.left);
12
+ Data right = dfs(root.right);
13
+ if (left.d > right.d) return new Data(left.root, 1 + left.d);
14
+ if (left.d < right.d) return new Data(right.root, 1 + right.d);
15
+ return new Data(root, 1 + left.d);
16
17
18
+ class Data {
19
+ TreeNode root;
20
+ int d;
21
22
+ public Data(TreeNode root, int d) {
23
+ this.root = root;
24
+ this.d = d;
25
26
27
+}
0 commit comments