236 Lowest Common Ancestor of a Binary Tree – Medium
Problem:
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4Thoughts:
Solutions:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
}
if (left != null) {
return left;
}
else {
return right;
}
}
}Previous235 Lowest Common Ancestor of a Binary Search Tree – EasyNext237 Delete Node in a Linked List – Easy
Last updated