mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «236. Lowest Common Ancestor of a Binary Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
e8d15a5bfa
commit
3a5d2ec0e6
1 changed files with 24 additions and 0 deletions
24
java/lowest-common-ancestor-of-a-binary-tree.java
Normal file
24
java/lowest-common-ancestor-of-a-binary-tree.java
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
class Solution {
|
||||||
|
public TreeNode lowestCommonAncestor(TreeNode node, TreeNode p, TreeNode q) {
|
||||||
|
if (node == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.val == p.val || node.val == q.val) {
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
var left = lowestCommonAncestor(node.left, p, q);
|
||||||
|
var right = lowestCommonAncestor(node.right, p, q);
|
||||||
|
|
||||||
|
if (left == null) {
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (right == null) {
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue