I have written a code for finding least common ancestor of nodes in binary tree but it seems to return null
instead of the LCA.
My algorithm is as below.
- Recursively find the ancestor in left and right branch of tree
A node where left as well as right tree has matching elements in the LCA.
public class LCA { public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) { if (root == null) { return null; } BinaryTreeNode left = root.getLeft(); BinaryTreeNode right = root.getRight(); if (left != null && (left == node1 || left == node2)) { return root; } if (right != null && (right == node1 || right == node2)) { return root; } if (( findLCA(left, node1, node2) != null) && (findLCA(right, node1, node2) != null)) { return root; } return null; }}
What could be the problem with this code?
I think I am able to fix it. I added another condition to see if my recursive findLCA is returning something. If so I return the same value further which fixed the issue. Plz provide your comments if this design is ok.
public static BinaryTreeNode findLCA( BinaryTreeNode root, BinaryTreeNode node1 , BinaryTreeNode node2) { if (root == null) { return null; } BinaryTreeNode left = root.getLeft(); BinaryTreeNode right = root.getRight(); BinaryTreeNode lcaNode1; BinaryTreeNode lcaNode2; if (left != null && (left == node1 || left == node2)) { return root; } if (right != null && (right == node1 || right == node2)) { return root; } lcaNode1 = findLCA(left, node1, node2); lcaNode2 = findLCA(right, node1, node2); if (( lcaNode1 != null) && lcaNode2 != null) { return root; } if (lcaNode1 != null) { return lcaNode1; } if (lcaNode2 != null) { return lcaNode2; } return null; }