一刷
Version #1 One pass recursion
Time O(N)
Space O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
class Pair {
int maxDepth;
TreeNode lca;
public Pair(int maxDepth, TreeNode lca) {
this.maxDepth = maxDepth;
this.lca = lca;
}
}
public TreeNode lcaDeepestLeaves(TreeNode root) {
Pair result = helper(root, 0);
return result.lca;
}
private Pair helper(TreeNode node, int depth) {
if (node == null) {
return new Pair(-1, null);
}
depth++;
if (node.left == null && node.right == null) {
return new Pair(depth, node);
}
Pair left = helper(node.left, depth);
Pair right = helper(node.right, depth);
if (left.maxDepth > right.maxDepth) {
return left;
}
if (left.maxDepth < right.maxDepth) {
return right;
}
return new Pair(left.maxDepth, node);
}
}
No comments:
Post a Comment