Very simple tree problem, somehow the result is null (which should be 1, since 1 is 2 & 3's parent node), cannot find the cause. The method itself already pass the Leetcode online judge.
Here is the link to the problem:
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: βThe lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).β
public class LowestCommonAncestor2 {
public static TreeNode mockTree() {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
node1.left = node2;
node1.right = node3;
return node1;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode t1, TreeNode t2) {
if (root == null || root == t1 || root == t2) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, t1, t2);
TreeNode right = lowestCommonAncestor(root.right, t1, t2);
if (left != null && right != null)
return root;
if (left != null)
return left;
if (right != null)
return right;
return null;
}
public static void main (String [] args) {
LowestCommonAncestor2 test = new LowestCommonAncestor2();
TreeNode root = mockTree();
TreeNode target1 = new TreeNode(2);
TreeNode target2 = new TreeNode(3);
TreeNode result = test.lowestCommonAncestor(root, target1, target2);
System.out.println(result);
}
}
and the TreeNode are defined as following:
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}