|
| 1 | +import 'dart:collection'; |
| 2 | +import 'dart:math'; |
| 3 | + |
| 4 | +class TreeNode { |
| 5 | + int val; |
| 6 | + TreeNode? left; |
| 7 | + TreeNode? right; |
| 8 | + TreeNode([this.val = 0, this.left, this.right]); |
| 9 | + |
| 10 | + @override |
| 11 | + String toString() { |
| 12 | + return 'TreeNode{val: $val}'; |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +class LcaResult { |
| 17 | + int depth; |
| 18 | + TreeNode? lca; |
| 19 | + LcaResult(this.depth, this.lca); |
| 20 | +} |
| 21 | + |
| 22 | +class Solution { |
| 23 | + LcaResult _dfs(TreeNode? node) { |
| 24 | + if (node == null) { |
| 25 | + return LcaResult(-1, null); |
| 26 | + } |
| 27 | + |
| 28 | + LcaResult leftResult = _dfs(node.left); |
| 29 | + LcaResult rightResult = _dfs(node.right); |
| 30 | + |
| 31 | + int currentDepth = max(leftResult.depth, rightResult.depth) + 1; |
| 32 | + |
| 33 | + if (leftResult.depth > rightResult.depth) { |
| 34 | + return LcaResult(currentDepth, leftResult.lca); |
| 35 | + } else if (rightResult.depth > leftResult.depth) { |
| 36 | + return LcaResult(currentDepth, rightResult.lca); |
| 37 | + } else { |
| 38 | + // equal |
| 39 | + return LcaResult(currentDepth, node); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + TreeNode? lcaDeepestLeaves(TreeNode? root) { |
| 44 | + if (root == null) { |
| 45 | + return null; |
| 46 | + } |
| 47 | + LcaResult result = _dfs(root); |
| 48 | + return result.lca; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +TreeNode? buildTree(List<int?> values) { |
| 53 | + if (values.isEmpty || values[0] == null) { |
| 54 | + return null; |
| 55 | + } |
| 56 | + |
| 57 | + TreeNode root = TreeNode(values[0]!); |
| 58 | + Queue<TreeNode> queue = Queue<TreeNode>(); |
| 59 | + queue.add(root); |
| 60 | + int i = 1; |
| 61 | + |
| 62 | + while (queue.isNotEmpty && i < values.length) { |
| 63 | + TreeNode current = queue.removeFirst(); |
| 64 | + |
| 65 | + if (i < values.length && values[i] != null) { |
| 66 | + current.left = TreeNode(values[i]!); |
| 67 | + queue.add(current.left!); |
| 68 | + } |
| 69 | + i++; |
| 70 | + |
| 71 | + if (i < values.length && values[i] != null) { |
| 72 | + current.right = TreeNode(values[i]!); |
| 73 | + queue.add(current.right!); |
| 74 | + } |
| 75 | + i++; |
| 76 | + } |
| 77 | + return root; |
| 78 | +} |
| 79 | + |
| 80 | +void main() { |
| 81 | + final solution = Solution(); |
| 82 | + |
| 83 | + List<int?> values1 = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]; |
| 84 | + TreeNode? root1 = buildTree(values1); |
| 85 | + TreeNode? lca1 = solution.lcaDeepestLeaves(root1); |
| 86 | + print("Example 1 LCA: ${lca1?.val}"); // Expected output: 2 |
| 87 | + |
| 88 | + List<int?> values2 = [1]; |
| 89 | + TreeNode? root2 = buildTree(values2); |
| 90 | + TreeNode? lca2 = solution.lcaDeepestLeaves(root2); |
| 91 | + print("Example 2 LCA: ${lca2?.val}"); // Expected output: 1 |
| 92 | +} |
0 commit comments