一刷 05/2022
Version #1 Recursion
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode[] result = new TreeNode[1];
countTarget(root, p, q, result);
return result[0];
}
private int countTarget(TreeNode node, TreeNode p, TreeNode q, TreeNode[] result) {
if (node == null) {
return 0;
}
int left = countTarget(node.left, p, q, result);
if (left == 2) {
return left;
}
int right = countTarget(node.right, p, q, result);
if (right == 2) {
return right;
}
int count = left + right;
if (node == p || node == q) {
count++;
}
if (count == 2) {
result[0] = node;
}
return count;
}
}
No comments:
Post a Comment